Scaling to a fixed point in KineticJS

前端 未结 4 910
鱼传尺愫
鱼传尺愫 2020-12-09 00:10

I\'m having some problems with scaling a container to a fixed point.
In my case I\'m trying to scale (zoom) a stage to the mouse cursor.

Here is a way to do with

4条回答
  •  旧时难觅i
    2020-12-09 00:42

    After a lot of struggling and searching and trying, using the tip provided by @Eric Rowell and the code posted in the SO question Zoom in on a point (using scale and translate) I finally got the zooming in and out of a fixed point working using KineticJS.

    Here's a working DEMO.

    And here's the code:

    var ui = {
        stage: null,
        scale: 1,
        zoomFactor: 1.1,
        origin: {
            x: 0,
            y: 0
        },
        zoom: function(event) {
            event.preventDefault();
            var evt = event.originalEvent,
                mx = evt.clientX /* - canvas.offsetLeft */,
                my = evt.clientY /* - canvas.offsetTop */,
                wheel = evt.wheelDelta / 120;
            var zoom = (ui.zoomFactor - (evt.wheelDelta < 0 ? 0.2 : 0));
            var newscale = ui.scale * zoom;
            ui.origin.x = mx / ui.scale + ui.origin.x - mx / newscale;
            ui.origin.y = my / ui.scale + ui.origin.y - my / newscale;
    
            ui.stage.setOffset(ui.origin.x, ui.origin.y);
            ui.stage.setScale(newscale);
            ui.stage.draw();
    
            ui.scale *= zoom;
        }
    };
    
    $(function() {
        var width = $(document).width() - 2,
            height = $(document).height() - 5;
        var stage = ui.stage = new Kinetic.Stage({
            container: 'container',
            width: width,
            height: height
        });
        var layer = new Kinetic.Layer({
            draggable: true
        });
        var rectX = stage.getWidth() / 2 - 50;
        var rectY = stage.getHeight() / 2 - 25;
    
        var box = new Kinetic.Circle({
            x: 100,
            y: 100,
            radius: 50,
            fill: '#00D200',
            stroke: 'black',
            strokeWidth: 2,
        });
    
        // add cursor styling
        box.on('mouseover', function() {
            document.body.style.cursor = 'pointer';
        });
        box.on('mouseout', function() {
            document.body.style.cursor = 'default';
        });
    
        layer.add(box);
        stage.add(layer);
    
        $(stage.content).on('mousewheel', ui.zoom);
    });​
    

提交回复
热议问题