Preston Hager
Preston Hager

Reputation: 1611

SVG Rotate Element While Animating svgjs

I'm using Javascript, Jquery, SVG, and SVG.js right now. I would like to rotate a circle about its origin while it's animating. The animation is doing the same thing, so I could use some sort of step function but I couldn't find anything. The problem is that with my current solution the animation is janky, it has to stop the animation, rotate the circle, and then start it again. Which in sequence has too much of a delay and causes a wiggling motion. Here's the setup code:

var draw = SVG('svg');
var innerCircle = draw.group().addClass("atom0g0").move(100,100);
innerCircle.circle(100).addClass("atom0p0").center(0, 0).attr({ fill: "white", stroke: "blue", "stroke-dasharray": "10" });
innerCircle.animate(6000).rotate(360, 0, 0).loop();

And the executing code right now, which I need to change to something is here:

var elms = $(".atom"+atom.atom_id.toString()+"g0");
for (var j=0; j < elms.length; j++) {
  // this is the problem, too much of a delay, therefore causing a wiggle motion.
  elms[j].instance.animate().stop();
  elms[j].instance.rotate(step, 0, 0);
  elms[j].instance.animate(6000).rotate(360, 0, 0).loop();
}

Here's the CodePen that I'm working on right now to make it: Current Version or Bugged Version

In short (if you just skipped to the end here) I need to rotate a circle without stopping the animation of the circle completely. I know that play(), pause() doesn't work because I can't call rotate() while the animations paused.

Upvotes: 5

Views: 1079

Answers (1)

entio
entio

Reputation: 4253

Accepted answer:

Try to wrap your element with one more element and animate them separately.


One of the solutions is to change this line:

elms[j].instance.rotate(Math.random()*360, 0, 0);

into that:

elms[j].instance.animate(1000).rotate(Math.random()*360, 0, 0);

This way rotation will be animated.

Codepen: https://codepen.io/soentio/pen/POVLYV


Other of the possible solutions i to utilise css for your transitions. By adding following line:

#svg > g {
    transition: transform 1s ease-in-out;
}

you make sure that whenever a group (that is direct children of your svg root node) is rotated, it's gonna be animated smoothly.

CodePen: https://codepen.io/soentio/pen/gXqqNQ

Advantage of this approach is that whatever your rotation is, browser picks the shortest path.


Bonus: I believe in superiority od css animations ( ;-) ) and inspired by your code made you a little codepen fiddle: https://codepen.io/soentio/pen/YEBgyj Maybe your goals are to be achieved with css only?

Upvotes: 3

Related Questions