Zooming into where mouse pointer is

I'm trying to work out how the user can use the mouse wheel to zoom in and out of the screen with the mouse pointer being the centre of zooming. I nearly have it working, except that after zooming, the screen content follows the pointer around as you move it. I can't work out the math / code to offset this. I need to use the translate / scale functions for my project. Thanks!

void setup(){

float zoom=1;

void draw(){






void mouseWheel(MouseEvent event) {
  float e = event.getCount();



  • Can't you store the position of the mouse when you zoom, and then zoom into that instead of the current mouse position?

  • funny I tried that - but in my project I'm using the mouse wheel for zooming, and tried using the mouseWheel() method to 'flag' when zooming and store x,y coordinates, but lots of flickering and jumping about - because of how and when mouseWheel() is called probably.. I'll have another go..

  • this is the closest I can get it.. It works, but jumps on the first wheel movement, and then works as wanted.. can't get rid of the jumping..

    float wheelCount = 0;
    float mx=0;
    float my=0;
    float zoom=1;
    void setup() {
      size(500, 500);
    void draw() {
      if (wheelCount != 0) {
        wheelCount = 0; 
      translate(mx, my);
      translate(-(mx), -(my));
      ellipse(20, 200, 500, 300);
      rect(200, 400, 300, 300);
      ellipse(400, 200, 100, 100);
    void mouseWheel(MouseEvent event) {
      wheelCount = event.getCount();
  • Answer ✓

    In line 16 you have /10 - not sure why

    But it would ignore most of the wheel movement or make it weaker

    Consider apply an easing for mx,my and zoom

    That means that you bot jump there but smoothly walk the values to their new value

    I can’t remember it, but in theory, set newMx in line 14 (plus and minus might be wrong: )

    mx = mx + (mx-newMx) * 0.1;

    0.1 tells how much slower the movement is

  • thanks for that - I've actually come up with a better solution anyway - after the user drags / navigates around the image space - that becomes the new centre of focus for zooming - rather than the current mouse pos - is much more intuitive and solves the wheel updating problem :)

  • Can you please post it

Sign In or Register to comment.