Search code examples
javascriptjqueryzoomingkineticjs

Zooming in and out on a point


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.


Solution

  • 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.