snap.svg

snapsvg - point of origin for scale/rotate after transform


I'm currently failing to understand how the point of origin works when scaling and rotating.

for instance, if I was to scale a 10x10 rectangle around its centre, I would expect I would have to get the rectangles last transform details (x and y), get the height and width of the rectangle and divide them by 2 and add them to the x and y but that just doesn't work.

Using SnapSVG I use the Snap.Matrix() method to create the matrix based on the previous transform:

var data = activeElement.data('originalMatrix');
var s = size/50; // size is a number from 1-100, defaulted to 50
var matrix = new Snap.Matrix(1,0,0,1,data.dx,data.dy);
matrix.rotate(data.rotate);
matrix.scale(s,s);

I under stand that for both rotate and scale methods accept a point of origin but I cannot work out how to calculate these values. Anyone know?


Solution

  • I think typically element.getBBox() suffices for most basic needs. But for more complex situations where there may be an existing transformation affecting the element, getBBox doesn't take this into account.

    You could try

    element.getBBox(1);
    

    In the comments, the extra parameter is 'isWithoutTransform' which seems counterintuitive to me, but it does help a bit..

    jsfiddle (this may skip a little on drag, and I wonder if its due to offset of text element vs bounding centre)

    jsfiddle May also help that has a plugin.

    Ultimately for more complex interactions, I would tend to try not to rely on matrices (ie getting values from them), and control the variables yourself.

    That would mean storing you rotate/scale/tx/ty and setting all of them yourself each time (ie one updateTransform method), via one Snap transformString (almost like a game).

    I also started a toolkit a while back that was never finished, but has some useful bits if you ever want to trawl through (see snaptoolkit.js)

    snaptoolkit in progress