我正在尝试用d3.js创建一个互动的财富轮,它可以在移动设备上工作。以下是我迄今为止一直在做的工作:http://plnkr.co/edit/JBJ1odoGvfWFODuIRqKZ
svg.on("mousemove", function(d) {
if (isDown){
var angleDeg = Math.atan2(lastY - d3.event.y, lastX - d3.event.x) * 180 / Math.PI;
lastX = d3.event.x;
lastY = d3.event.y;
curAngle = angleDeg;
svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ") rotate(" + curAngle + "," + 0 + "," + 0 + ")");
}
});现在,我正在尝试使它,以便您可以点击-拖动饼图切片,并“旋转”,只要鼠标是向下的。我用Math.atan2来得到圆圈上两点之间的角度,并相应地改变饼图的角度。我所拥有的似乎已经差不多了,但还是有一个滞后/抖动的现象。我能做些什么来使它看起来像这样吗?:5/
理想情况下,从长远来看,我希望mouseup事件能够为旋转创造某种速度,而任何向上指向的片段都可以被查询。
但就目前而言,我只是试图创造一个顺利的拖拽。
发布于 2016-05-12 10:18:38
为什么你的“紧张”是因为你使用鼠标坐标相对于另一个。你要做的是使用一个固定点,即车轮的中心。
因此,与使用d.event.x/y更新lastX和lastY不同,只需将其保持如下:
var lastX = width/2; //center points of circle
var lastY = height/2;并在算法中使用如下所示:
if (isDown) {
var thisX = d3.event.x - lastX,
thisY = d3.event.y - lastY;
var angleDeg = Math.atan2(lastY - d3.event.y, lastX - d3.event.x) * 180 / Math.PI;
svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ") rotate(" + angleDeg + "," + 0 + "," + 0 + ")");
}我把它放在JSFiddle上,因为plnkr没有正常工作,鼠标事件等等:https://jsfiddle.net/thatOneGuy/ourpo8p7/1/
就算是这样也不完美。
基本上,这里发生的是,它得到鼠标坐标,然后旋转到那个坐标。但是你不想这样,你只希望它在你移动鼠标的时候移动,即使这样,你也只希望它按你移动光标的数量移动,而不是跳到光标(如果这是有意义的话:P )。
所以你要做的是从0开始,如果你在鼠标向下移动光标,保存旋转的位置,所以当你再次开始的时候,你可以从你停止的地方开始。这很难解释。
无论如何,当鼠标倒下时,保存鼠标坐标与圆心之间的夹角:
var thisX = d3.event.x - lastX,
thisY = d3.event.y - lastY;
curAngle = Math.atan2(lastY - d3.event.y, lastX - d3.event.x)
if (curAngle < 0) curAngle += 2 * Math.PI; //make sure its positive
curAngle = curAngle * 180 / Math.PI; //change to degrees现在鼠标移动,你必须从计算的角度取这个值,所以你从0开始,但添加最后一个角(如果有的话)计算时,你旋转车轮。
var thisX = d3.event.x - lastX,
thisY = d3.event.y - lastY;
angleDeg = Math.atan2(lastY - d3.event.y, lastX - d3.event.x) // * 180 / Math.PI) - curAngle
if (angleDeg < 0) angleDeg += 2 * Math.PI;
angleDeg = angleDeg * 180 / Math.PI;
angleDeg = angleDeg - curAngle + finishAngle; //reset to 0 and add last rotation calculated
if (angleDeg < 0) angleDeg += 360;
d3.select('#degrees').text(Math.round(angleDeg))
svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ") rotate(" + angleDeg + "," + 0 + "," + 0 + ")");最后,计算出mouseup时使用的旋转角度。
finishAngle = angleDeg;https://stackoverflow.com/questions/37178251
复制相似问题