Night #1: Zoom and Pan in 2D

This came up in my course “Introduction to Computational Media” this year. How does one pan and/or zoom in a 2D Processing world? We could certainly introduce P3D into the mix, but there is a nice, elegant way we can create the effect of panning and zooming and still live in 2D. Here’s how it works.

First, you need to make sure you translate to the center of your window.

  translate(width/2, height/2);

Then you can use the scale() function to scale the world according to a percentage (i.e. 2.0 is 200%, 0.5 is 50%). We’ll use a variable called zoom.

  float zoom = 1.5;  // 150%
  scale(zoom);

Then we can translate additionally to pan according to some offset.

  float offsetX = 100;  // Some arbitrary offset
  float offsetY = 0;
  translate(offsetX,offsetY);

Here is an example (running in processing.js) that allows the user to pan around a design by dragging the mouse, and zoom in and out using key presses.

Source: PanZoom2D.zip

  • Miguel Ángel de Frutos Carro

    Oh, really interesting! Thanks for sharing it.

  • http://twitter.com/nsa4ever nsa

    :)  

  • Wanderingbear

    Cool example! If possible can you link to a .pde instead of a .zip file for some of these. I realize that may not be possible for some of your examples. Thanks!

  • Julien Castelain

    Nice stuff thanks. I changed this in the draw method to give a fading effect :
       //background(255);
       fill(255, 45);      pushMatrix();  // …  translate(width / 2, height / 2);    rect(0, 0, width, height); 

    cheers

  • http://twitter.com/dgou Doug Philips

    Very cool.
    I’m a bit confused as to how to handle the mouse coordinates in a panned and scanned world though. Say my application has ‘rollovers’ and I want to know what object(s) are under the mouse?

  • http://twitter.com/RichardvanDuijn Richard van Duijn

    Very nice!
    Question: Is there a formula to transform sceen cooridnates to model coordinates when using scale and translate? I’ve been struggling with this for some time now. But haven’t been able to solve it.

  • Anonymous
  • Anonymous

    This is a hard problem, you need to know the actual pixel XY and dimensions of the shapes after they’ve been translated and scaled.  screenX (http://processing.org/reference/screenX_.html) can help you, and you can also use the scale variable itself to manually adjust dimensions.