Mark
Mark

Reputation: 14930

KineticJS and pinch and zoom

I would like to achieve this effect outlined here: http://www.html5canvastutorials.com/labs/html5-canvas-multi-touch-scale-stage-with-kineticjs/

But on a Layer in KineticJS

I have already got it working to a degree (using basically the same code as in the link), but it seems the Layer scales around the 0,0 origin point and I cannot see any doco about changing the transform origin?

How can I effectively pinch and zoom a Layer such that it scales around it center point?

Upvotes: 2

Views: 1499

Answers (1)

pillar15
pillar15

Reputation: 576

I made a plugin for this kind of behavior: https://github.com/eduplus/pinchlayer

It is probably a little outdated now with the recent changes, but the logic in layerTouchMove function is most likely still sound. Here:

var touch1 = event.touches[0];
var touch2 = event.touches[1];  

if (touch1 && touch2) {
 self.setDraggable(false);
 if (self.trans != undefined) { self.trans.stop(); }
    if (self.startDistance === undefined) {
        self.startDistance = self.getDistance(touch1, touch2);
        self.touchPosition.x = (touch1.clientX + touch2.clientX) / 2;
        self.touchPosition.y = (touch1.clientY + touch2.clientY) / 2;
        self.layerPosition.x = (Math.abs(self.getX()) + self.touchPosition.x) / self.startScale;
        self.layerPosition.y = (Math.abs(self.getY()) + self.touchPosition.y) / self.startScale;
    }
    else {
        var dist = self.getDistance(touch1, touch2);
        var scale = (dist / self.startDistance) * self.startScale;
        if (scale < self.minScale) { scale = self.minScale; }
        if (scale > self.maxScale) { scale = self.maxScale; }
        self.setScale(scale, scale);
        var x = (self.layerPosition.x * scale) - self.touchPosition.x;
        var y = (self.layerPosition.y * scale) - self.touchPosition.y;
        var pos = self.checkBounds({ x: -x, y: -y });
        self.setPosition(pos.x, pos.y);
        self.draw();
     }

Basically it will record the starting point and the distance (how long the pinch is) and then scale and set the layer position accordingly. Hope this helps.

Upvotes: 2

Related Questions