0

I'm trying to make a stage that can be zoomed by mousewheel. I'm using the stage.scale and jquery event. But I have not been able to make the zoom done with the mouse pointer as center. So when my mouse is on a point, I want to zoom in it centrically.

I've make this example, that doesen't work for now : http://fiddle.jshell.net/rr7pLapz/1/

Here is my zoom function :

$("#cont").bind('mousewheel', function(e) {
        var x = e.offsetX;
        var y = e.offsetY;
        if (e.originalEvent.wheelDelta > 0) {
                STAGE.scale({
                    x:STAGE.scale().x+1,
                    y:STAGE.scale().y+1
                });
                STAGE.x(-x + 500/(STAGE.scale().x));
                STAGE.y(-y + 350/(STAGE.scale().y));
                STAGE.batchDraw();
        }
        else {
            if (STAGE.scale().x > 1) {
                STAGE.x(-x + 500/(STAGE.scale().x));
                STAGE.y(-y + 350/(STAGE.scale().y));
                STAGE.scale({
                    x:STAGE.scale().x-1,
                    y:STAGE.scale().y-1
                });
                STAGE.batchDraw();
            }
        }
});

Can you help ? Many thanks.

FitzFish
  • 8,557
  • 2
  • 30
  • 39
  • 1
    Set the scaling point to the mouse position. The scaling point is offsetX and offsetY. – markE Sep 14 '14 at 01:30

1 Answers1

0

Here is a manual way to do it:

First, store the mouse position in stage coordinates. Then apply the scale, and get the new mouse position in stage coordinates. Then offset the stage by oldPosition - newPosition. This effectively puts the same point in the stage back under the mouse.

Or as Mark said, you can do it via layer offsets. Though that might not be the most convenient way to do it, depending how your project is setup to use kinetic's features. See these links: Scaling to a fixed point in KineticJS KineticJS Canvas - Scale group from center point

Also some side notes:

  • You have some duplication in that code. Why not only have one line under each wheelDelta condition, to determine the newScale, then use that variable in the following lines.
  • I've found that it makes a smooth zoom to do scale *= 1.2 and scale /= 1.2 rather than the straight adding you're doing there. Just a suggestion.
Community
  • 1
  • 1
V. Rubinetti
  • 1,324
  • 13
  • 21
  • Hi, thank you for your help. Your first link was hepfull, with a bit of update (setScale(x,y) -> scale({x:x, y:y}) etc), I used it raw. – FitzFish Sep 14 '14 at 21:52