我使用以下代码来为我的速度计移动 Canvas 中的图片。
var meter = new Image,
needle = new Image;
window.onload = function () {
var c = document.getElementsByTagName('canvas')[0];
var ctx = c.getContext('2d');
setInterval(function () {
ctx.save();
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(c.width / 2, c.height / 2);
ctx.drawImage(meter, -165, -160);
ctx.rotate((x * Math.PI / 180);
/ x degree
ctx.drawImage( needle, -13, -121.5 );
ctx.restore();
},50);
};
meter.src = 'meter.png';
needle.src = 'needle.png';
}
但是我想将针慢慢移动到我输入的程度,例如速度测试网页。任何想法? 谢谢。
最佳答案
像这样的东西应该可以工作:
var meter = new Image,
needle = new Image;
window.onload = function () {
var c = document.getElementsByTagName('canvas')[0],
ctx = c.getContext('2d'),
x, // Current angle
xTarget, // Target angle.
step = 1; // Angle change step size.
setInterval(function () {
if(Math.abs(xTarget - x) < step){
x = xTarget; // If x is closer to xTarget than the step size, set x to xTarget.
}else{
x += (xTarget > x) ? step : // Increment x to approach the target.
(xTarget < x) ? -step : // (Or substract 1)
0;
}
ctx.save();
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(c.width / 2, c.height / 2);
ctx.drawImage(meter, -165, -160);
ctx.rotate((x * Math.PI / 180); // x degree
ctx.drawImage( needle, -13, -121.5 );
ctx.restore();
},50);
};
dial.src = 'meter.png';
needle.src = 'needle.png';
}
我这里用的是简写if/else
来判断x
是否加1
,减去1
,或者什么也不做。在功能上,这与:
if(xTarget > x){
x += step;
}else if(xTarget < x){
x += -step;
}else{
x += 0;
}
但它更短,而且在我看来,只要您知道 if ( ternary operator) 的简写形式,就同样易于阅读。
请记住,此代码假定 x
是一个整数值(因此,不是 float ,只是一个四舍五入的 int)。
关于html - Canvas 测速仪指针怎么慢慢移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13948410/