我正在尝试使用d3.js为量规针设置动画,但最终会产生一个奇怪的动画。我已经从互联网上做了一些搜索,但我无法弄清楚我可以用什么解决方案来解决问题。
function createNeedle(sampleAngle){
topX = centerX - Math.cos(sampleAngle) * triLength
topY = centerY - Math.sin(sampleAngle) * triLength
leftX = centerX - 10 * Math.cos(sampleAngle - Math.PI / 2)
leftY = centerY - 10 * Math.sin(sampleAngle - Math.PI / 2)
rightX = centerX - 10 * Math.cos(sampleAngle + Math.PI / 2)
rightY = centerY - 10 * Math.sin(sampleAngle + Math.PI / 2)
return " M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
}
//animate the needle
d3.select('.moveNeedle')
.attr('d', createNeedle(sampleAngle1))
.transition()
.duration(2000)
.attr('d', createNeedle(sampleAngle2));
答案 0 :(得分:1)
如果您应用transform="rotate()"
而不是重新绘制路径,则可以让您的生活更加轻松。
尽管如此,您需要提供自定义Tween功能,因为标准d3.interpolateTransformSvg会以意想不到的方式执行。
var topX = centerX - triLength,
topY = centerY,
leftX = centerX,
leftY = centerY + 10,
rightX = centerX,
rightY = centerY - 10;
function rotateNeedle(sampleAngle){
return "rotate(" + sampleAngle + "," + centerX + "," + centerY + ")";
}
d3.select('.moveNeedle')
// only draw once
.attr('d', "M" + leftX + " " + leftY + " " + topX + " " + topY + " " + rightX + " " + rightY)
// supply angles in degrees!
.attr('transform', rotateNeedle(sampleAngle1))
.transition()
.duration(2000)
.attrTween('transform', function () {
var i = d3.interpolate(sampleAngle1, sampleAngle2)
return function (t) {
return rotateNeedle(i(t));
};
});