排除无限循环错误

时间:2014-12-11 14:17:05

标签: javascript html5 canvas

我试图在画布上随机x,y绘制一个图像数组,但它给了我一个无限循环....这是我的代码

var fruits = ["fruit1.png", "fruit2.png", "fruit3.png", "fruit4.png"];
var monsterReady1 = true;
var draw = function() {
    for (var i = 0; i < fruits.length; i++) {
        monsterImage1 = new Image();
        monsterImage1.onload = function () {
            monster1.x = (Math.random() * (canvas.width - 100));
            monster1.y = (Math.random() * (canvas.height - 100));
            ctx.drawImage(this, monster1.x, monster1.y);
        };
        monsterImage1.src = fruits[i];
    }
};

var render = function() {
    if (monsterReady1) {
        draw();
    }

    var main = function () {
        update();
        render();
        requestAnimationFrame(main);
    };

1 个答案:

答案 0 :(得分:2)

你在main()函数中有递归。这是requestAnimationFrame()的正常行为。将每个帧的画布称为无限函数是正常的。

render()执行时也会有递归。您不需要一次又一次地调用渲染。从render()正文

传递渲染电话
var render = function(){
    if (monsterReady1) {
        draw();
    }

    var main = function () {
        update();
        render();                            // THIS is error. You should not call render again
        requestAnimationFrame(main);         // This will call main function infinite loop. Expected.
    }   
};

//render();                                    // Better to call it here

顺便提一下,您提供的代码存在语法错误。你错过了一个结束括号