有人可以解释一下如何在不更改 setTimeout 的情况下更改我的英雄动画吗?我的意思是如何使英雄动画比所有 Canvas 慢。我所说的动画是指改变帧
function draw() {
if (hero.ready){
ctx.clearRect (0 , 0, 500 , 500 );
ctx.shadowColor = "rgba( 0, 0, 0, 0.1 )";
ctx.shadowOffsetX = 15;
ctx.shadowOffsetY = -10;
ctx.drawImage(image[hero.image],hero.frames * hero.sizeX, 0, hero.sizeX, hero.sizeY, hero.posX, hero.posY, hero.sizeX, hero.sizeY);
}
hero.frames++;
if (hero.frames >= 2) hero.frames = 0;
setTimeout( draw, 1000 / 5 );
}
JSFIDDLE完整示例。
最佳答案
为了澄清“增量时间”的概念,如果您只是简单地增加计数器而不根据实际时间进行缩放,那么它的增加速度将与调用 draw
一样快。然而,通过缩放它,您可以保证每秒一定数量的帧。这样,您始终可以确保动画的速度如您所愿。您可以将阈值设置为例如 500 毫秒(每半秒一帧),依此类推。
var counter = 0;
function draw() {
// deltaTime is how you plan on counting real seconds
// against your frame ticks
counter += deltaTime;
...
// threshold would be your delay
if (counter >= threshold)
{
hero.frames++;
if (hero.frames >= 2) hero.frames = 0;
counter = 0;
}
}
setInterval( draw, 1000 / 5 );
关于javascript - 改变更新速度而不改变循环速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18111909/