使用AnimationFrame动画速度如此之慢的原因是什么?

时间:2015-07-06 06:17:02

标签: javascript canvas

我正在学习Javascript和画布动画。尝试用动画做一些事情来升级我的技能,这次是它的简单老虎机。

如果有人可以解释我为什么这台"机器"那将是很好的。太慢了?我做错了什么?

我尝试使用requestAnimationFrame而不是SetInterval。

最后,对于你们中的某些人来说,我的代码可能很糟糕,但请记住,我只是在学习:)

function main(){ // This is the main function 

canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGTH;
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);

init();
canvas.addEventListener('click', function(){
    // update();
    // window.requestAnimationFrame(update);
    // setInterval(update, 100);
    update();
});
};

main();

function imgLoad(imgArray){
    var Images = [];
    imgArray.forEach(function(link){
        img = new Image();
        img.src = link;
        Images.push(img);
    });

    return Images;

};
function Reel(x ,y){  // This is my constructor with drawImage method
    var _this = this;
    _this.x = x;
    _this.y = y;
    _this.vel = 5;
    _this.counter = 20;

    this.changeY = function(){
        _this.y += _this.vel;
    };
    this.draw = function(){   // this function draws rows with images

    imgLoad(imgArray);

    img.addEventListener('load', function(){
        for(var i = 0; i < imgLoad(imgArray).length; i+=1){

        ctx.drawImage(imgLoad(imgArray)[i], _this.x, _this.y + i * canvas.height / 4, canvas.width / 5, canvas.height / 4);
        }
    });

};
function makeReels(){  // making the instances of Reel constructor

    for(var i = 0; i < 5; i+=1){
        reels.push(new Reel(canvas.width / 5 * i, 0));
    }
};
function init(){  // drawing first images
    makeReels();

    for(var i = 0; i < 5; i+=1){
        reels[i].draw();
    };
};
function update(){  // this is my update function the I'm redrawing images with new Y position

    for(var i = 0; i < 5; i+=1){

        (function(i){
        setTimeout(function(){
            ctx.clearRect(0,0,canvas.width,canvas.height);

        reels[i].changeY();
        reels[i].draw();
            }, 100 * i);
        })(i);
        };
        reels[0].counter --;

        if(reels[0].counter > 0){
            window.requestAnimationFrame(update);
        }
        else {
            window.cancelAnimationFrame(update);
            reels[0].counter = 20;

        }
    };

1 个答案:

答案 0 :(得分:2)

我已经将你的代码缩小了一点,这就是我所看到的:

function update(){
    for(var i = 0; i < 5; i+=1){
        //calculate stuff
        //draw stuff
        window.requestAnimationFrame(update);
    }
}

看起来每次调用update()时,再调用5次,然后每次调用update()5次。更新的调用次数将呈指数级增长。我怀疑这是你动画慢的原因。

我建议只使用requestAnimationFrame()来绘制内容,保持计算和变量操作。

示例

function myDrawFunction() {
    //Draw stuff here
    requestAnimationFrame(draw);
}

function myUpdateFunction () {
    //Here we will be more strict about when stuff are being updated.
    //i.e. here we care about the elapsed time since last update
}