简体   繁体   中英

Snap.svg - Rotate after drag not working

Hopefully this is a basic question and can be answered easily! Basically, I want to drag a shape then double click on it and rotate by 90deg. But once you move the shape from the start point the rotations go haywire. I have tried to recalculate the centre point for rotation like so...

var bbox = tri.getBBox();
tri.animate({
    transform: "R"+angle+"," + bbox.cx  + ","  + bbox.cy
}, 500)

See fiddle... http://jsfiddle.net/henryJack/hsfor158/7/ .

Any help much appreciated!

I think there's potentially two issues.

Firstly, transforming will overwrite any existing transformations, so you want to include the existing transform and then include the new one on top of that.

element.transform()

Will give the existing transform in place. So you can combine the old with the new.

tri.animate({
   transform: tri.transform() + "R"+angle+"," + bbox.cx  + ","  + bbox.cy
}, 500)

However, the 2nd issue I think is that getBBox() doesn't take into account transforms by default, and it will accumulate transforms, so you may want to store the transform somewhere on a double click and use that instead of transform().

There is a hidden parameter to Snaps getBBox(), if you give it getBBox(1), I think it will take into account it's local transform (I may be wrong on this, so if you need to know definitely, I would ask a new question on this specific topic, as it may take a bit of digging through source code...the source code calls the parameter isWithoutTransform, but I think it depends how you interpret this, have a play).

So you can combine the two...

var bbox = tri.getBBox(1);
angle += 90;
tri.animate({
    transform: tri.transform() + "r"+angle+"," + bbox.cx  + ","  + bbox.cy
}, 500);

jsfiddle

Possible better solution , there may be a better way though: If you need to take into account further transformations applied to outer elements (for example if its in a group which is transformed), it gets more complicated, and you will need to either add a function like getTransformedBBox OR maybe better, come up with an alternate solution, for example to drag an outer group and rotate the inner element . You could do this anyway as an alternate solution (add the element to a group, add the drag the group, but just rotate the element)!

2nd more reliable example by using an extra group

var triGroup = s.group( tri )
var angle = 0;
var rotate = function() {
    var bbox = tri.getBBox();
    angle += 90;
    bbox = tri.getBBox();
    tri.animate({
        transform: "r"+angle+"," + bbox.cx  + ","  + bbox.cy
    }, 500);
}

triGroup.dblclick(rotate);
triGroup.drag();

jsfiddle 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM