在为spritesheet设置动画时降低帧速率

时间:2017-02-20 12:08:57

标签: javascript animation

我一直试图为五帧精灵制作动画。我已经开始工作了,但是由于它只有五帧,所以它过快地通过帧。是否有一个选项在帧之间创建一个轻微的延迟,所以动画看起来不那么匆忙?

这是我用来为精灵表制作动画的代码。

    var canvas = document.querySelector("#openmind");
var context = canvas.getContext("2d");

//Loading Spritesheet
var myImage = new Image();
myImage.src = "img/sprites/foxsprite.png";
myImage.addEventListener("load", loadImage, false);

function loadImage(e) {
    animate();
}

//Setting size details for frmae
var shift = 0;
var frameWidth = 44.2;
var frameHeight = 72;
var totalFrames = 5;
var currentFrame = 0;

function animate() {

    context.clearRect(120, 25, 300, 300);
    //draw each frame + place them in the middle
    context.drawImage(myImage, shift, 0, frameWidth, frameHeight,
        120, 25, frameWidth, frameHeight);

    shift += frameWidth + 1;


    /*
     Start at the beginning once you've reached the
     end of your sprite!
     */
    if (currentFrame == totalFrames) {
        shift = 0;
        currentFrame = 0;
    }

    currentFrame++;

    requestAnimationFrame(animate);


}

1 个答案:

答案 0 :(得分:1)

使用计数器在更改帧之间产生延迟。

var counter = 0;

然后在你的循环中:

if(counter == 10){
   currentFrame++;
   counter = 0;
} else {
   counter++;
}