javascript D3.js 动画旋转
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13313043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3.js animate rotation
提问by frshca
I'm having trouble when I try to correctly execute a rotation animation using the D3.js library. The problem has to do with the point at which I want to rotate the element about.
当我尝试使用 D3.js 库正确执行旋转动画时遇到问题。问题与我想要旋转元素的点有关。
Here is a fiddle I made to show what I mean (in slow motion): http://jsfiddle.net/74mCb/
这是我用来展示我的意思的小提琴(慢动作):http: //jsfiddle.net/74mCb/
It seems like the source of the problem lies here:
问题的根源似乎在这里:
.attr("transform", "rotate(-60, 150,130)");
And then I rotate it like so:
然后我像这样旋转它:
.attr("transform", "rotate(40 150,130)");
I would like the butt of the needle to stay in position (to be the center of rotation), could someone please explain what I am doing wrong?
我希望针尖保持原位(成为旋转中心),有人可以解释一下我做错了什么吗?
Thanks!
谢谢!
回答by methodofaction
This is a bit tricky to grasp (I don't fully understand it myself) but D3 needs some help knowing how to interpolate between the two strings that represent your rotation.
这有点难以理解(我自己也不完全理解),但 D3 需要一些帮助来了解如何在代表您的旋转的两个字符串之间进行插值。
function turnNeedle()
{
needle
.transition()
.duration(2000)
.attrTween("transform", tween);
function tween(d, i, a) {
return d3.interpolateString("rotate(-60, 150, 130)", "rotate(60, 150, 130)");
}
}
d
is the datum, i
is the index, a
is the attribute in case you want to make this data-driven.
d
是数据,i
是索引,a
是属性,以防你想让这个数据驱动。
回答by nrabinowitz
Here's what I think is going on: per the SVG spec, the transform
这是我认为正在发生的事情:根据SVG 规范,转换
rotate(40 150,130)
is equivalent to:
相当于:
translate(150,130) rotate(40) translate(-150, -130)
It looks like D3 is animating the translation as well as the rotation - the internal d3.transform
representation of rotate(40 150,130)
is a rotate component + a translation component, so both are being included in the transition.
看起来 D3 正在为平移和旋转设置动画 - 的内部d3.transform
表示rotate(40 150,130)
是旋转组件 + 平移组件,因此两者都包含在过渡中。
The easiest fix here is to draw your needle at the origin, translate it with an outer g
element to the correct position, then rotate it:
这里最简单的解决方法是在原点画你的针,用外部g
元素将它平移到正确的位置,然后旋转它:
var needle = svg
.append("g")
.attr("class", "needle")
.attr("transform", "translate(150 , 130)")
.append("path")
.attr("class", "tri")
// your path may have been prettier
.attr("d", "M-3 0 L0 -130 L3 0 S3 5 0 5 S-3 5 -3 0 Z")
.attr("transform", "rotate(-60)");
then
然后
needle
.transition()
.duration(2000)
.attr("transform", "rotate(40)");
See working fiddle: http://jsfiddle.net/nrabinowitz/74mCb/1/