How to zoom-in to the point under the mouse cursor?

Hi,

I'd like to zoom-in to the point under the mouse cursor. I understand that to do so requires a translate and a scale transformation: the scale is pretty straightforward, but the translate has me stumped. The idea is to zoom-in, whilst maintaining the relative distance between the mouse cursor and other objects in the sketch.

I know that several libraries implement zooming and panning (e.g. giCentre Utilities), but I'd like to be able to understand the problem from first principles, without using Java's AffineTransform class, if possible.

Any help would be greatly appreciated. A basic sketch, which zooms-in but doesn't maintain the relative distance, follows:

float scaleFactor;

void setup()
{
  size(300, 300);

  scaleFactor = 1;
}

void draw()
{
  background(255);

  pushMatrix();

  scale(scaleFactor);

  fill(192);

  stroke(128);

  rect(10, 10, 100, 100);

  line(60, 10, 60, 110);

  line(10, 60, 110, 60);

  popMatrix();
}

void keyPressed()
{
  if (key == 'r')
  {
    scaleFactor = 1;
  }
}

void mouseWheel(MouseEvent e)
{
  scaleFactor += e.getAmount() / 100;

  if (scaleFactor < 1.0) scaleFactor = 1.0;

  if (scaleFactor > 2.0) scaleFactor = 2.0;
}
Tagged:

Answers

  • edited November 2013

    This was answered over on StackOverflow. Here's the updated sketch:

    float scaleFactor, translateX, translateY;
    
    void setup()
    {
      size(300, 300);
    
      scaleFactor = 1;
    
      translateX = 0;
    
      translateY = 0;
    }
    
    void draw()
    {
      background(255);
    
      pushMatrix();
    
      translate(translateX, translateY);
    
      scale(scaleFactor);
    
      fill(192);
    
      stroke(128);
    
      rect(10, 10, 100, 100);
    
      line(60, 10, 60, 110);
    
      line(10, 60, 110, 60);
    
      popMatrix();
    }
    
    void keyPressed()
    {
      if (key == 'r')
      {
        scaleFactor = 1;
    
        translateX = 0;
    
        translateY = 0;
      }
    }
    
    void mouseWheel(MouseEvent e)
    {
      scaleFactor += e.getAmount() / 100;
    
      translateX -= e.getAmount() * mouseX / 100;
    
      translateY -= e.getAmount() * mouseY / 100;
    }
    
Sign In or Register to comment.