简体   繁体   中英

Linear/Incremental rotation animation with transition

I'm trying to get a SVG shape to rotate using the transform attribute and the transition method in D3. Here is the jsfiddle containing an example: http://jsfiddle.net/TJd2a/

I'm using two buttons, Left and Right, to rotate the rectangle by incrementing by its angle by 45 or -45 degrees. When the shape reaches either 180 or -180 degrees, the transition rotates the shape the opposite way, rather than moving linearly to the next angle. Using console logging, I've found there is nothing wrong with the angles that my code is generating. It appears to be how D3 is dealing the transition, as the generated XML does not show the same angle as the current (eg. when at 225 degrees, D3 gives the rectangle a rotation of -135 instead).

From what I've read and understand from the documentation, I need to use a custom Tween, but I 'm not sure where to start with a custom tween as I cannot find any examples specific or similar examples to help me understand how it works.

Correct; you can use a custom tween to change the interpolator. D3 has a special interpolator for transforms , but it's not doing the right thing in your case. (I think that's probably a bug which should be fixed, so I filed issue 661 .) Here's an example using interpolateString instead:

d3.select("rect").transition().attrTween("transform", function(d) {
  return d3.interpolateString(
    "rotate("+ d.a +")",
    "rotate(" + (d.a += 45) + ")"
  );
});

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