我已經得到了它非常粗略的工作路徑動畫:http://jsfiddle.net/UT69H/18/
這真是戰戰兢兢,但它與路徑旋轉。請注意,我將mousemove處理程序移動到body元素,以便在鼠標移出本機外時不會突然停止。
bod.on "mousemove",() ->
if mousedown
pos = getPosHandle { x: d3.mouse(h[0][0])[0], y: d3.mouse(h[0][0])[1] }
pos1 = getPosHandle { x: d3.mouse(h[0][0])[0], y: d3.mouse(h[0][0])[1] - 1 }
pos2 = getPosHandle { x: d3.mouse(h[0][0])[0], y: d3.mouse(h[0][0])[1] + 1 }
ang = Math.round(Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180/Math.PI) - 90
h.attr "transform", "rotate(#{ang} #{pos.x} #{pos.y})"
h.attr "x", (pos.x - h.attr("width")/2)
h.attr "y", (pos.y - h.attr("height")/2)
這是一個好一點:http://jsfiddle.net/UT69H/19/
bod.on "mousemove",() ->
if mousedown
pos = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] }
pos1 = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] - 1 }
pos2 = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] + 1 }
ang = Math.round(Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180/Math.PI) - 90
h.attr "transform", "rotate(#{ang} #{pos.x} #{pos.y})"
h.attr "x", (pos.x - h.attr("width")/2)
h.attr "y", (pos.y - h.attr("height")/2)
您可以通過另外的間隔測試點出減少抖動:http://jsfiddle.net/UT69H/21/
bod.on "mousemove",() ->
if mousedown
pos = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] }
pos1 = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] - 4 }
pos2 = getPosHandle { x: d3.mouse(bod[0][0])[0], y: d3.mouse(bod[0][0])[1] + 4 }
ang = Math.round(Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180/Math.PI) - 90
h.attr "transform", "rotate(#{ang} #{pos.x} #{pos.y})"
h.attr "x", (pos.x - h.attr("width")/2)
h.attr "y", (pos.y - h.attr("height")/2)
如果我理解'getPointAtLength'正確,它計算兩個這樣的點之間的角度應該是一件微不足道的事情。 – Shmiddty
@Shmiddty路徑可以是貝塞爾曲線,所以角度不包含。 – Duopixel
@Duopixel如果您正在尋找沿路徑某處某點的「方向」,則可以通過簡單地抓住點之前的點和點之後的點並計算它們之間的角度來近似該點。顯然,你想要儘可能小的點之間的距離。 – Shmiddty