问题
I'm trying to have a circle follow an elliptical path that is rotated, using Snap.svg, but I've ran into a problem.
Using the getPointAtLength only returns the point of the path that is not rotated, so when I rotate the path, the circle will still follow the original path, before rotation.
var firstOrbit = s.path("M250,400a150,75 0 1,0 300,0a150,75 0 1,0 -300,0")
.attr({stroke: "#000", strokeWidth:"5", fill: "transparent"});
var len = firstOrbit.getTotalLength();
firstOrbit = firstOrbit.transform('r75,400,400');
var circleA = s.circle(0,0,10);
var startingPointA = Snap.path.getPointAtLength(firstOrbit, 0);
Snap.animate(0, len, function(value){
var movePoint = firstOrbit.getPointAtLength(value);
circleA.attr({ cx: movePoint.x, cy: movePoint.y });
}, 2000, mina.linear);
The problem is, that the ellipse rotates, but the path that circleA follows does not, so it follows a wrong path. Is there an easy way to fix this, or do I have to calculate the difference at each step of the animation?
回答1:
You have two possible solutions for this issue. Either you will have to put the <path>
and <circle>
inside a <g>
group and apply transformations to the group Or find actual point on path and then find the transformed point by applying the transformation matrix.
Solution 1
var len = firstOrbit.getTotalLength();
var circleA = s.circle(0,0,10);
var group = s.g(firstOrbit,circleA);
group = group.transform('r75,400,400');
JSFiddle
Solution 2
var pt = s.node.createSVGPoint();
Snap.animate(0, len, function(value){
var movePoint = firstOrbit.getPointAtLength(value);
pt.x = movePoint.x;
pt.y = movePoint.y;
movePoint = pt.matrixTransform(firstOrbit.node.getCTM());
circleA.attr({ cx: movePoint.x, cy: movePoint.y });
}, 2000, mina.linear);
JSFiddle
回答2:
Put both the circle and the path inside a group. Apply the transform/rotation to the group (instead of the path) so that both the circle and the path inherit the same transform. .
来源:https://stackoverflow.com/questions/27697757/svg-follow-rotated-path