gpt4 book ai didi

javascript - 解决无限循环错误

转载 作者:行者123 更新时间:2023-12-02 16:41:50 25 4
gpt4 key购买 nike

我试图在 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);
};

最佳答案

您在 main() 函数中进行了递归。这是 requestAnimationFrame() 的正常行为。通常无限调用该函数来每帧绘制 Canvas 。

render() 执行时也存在递归。您不需要一次又一次地调用 render。从 render() body 传递渲染调用

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

顺便说一句,您提供的代码存在语法错误。您错过了一个右括号

关于javascript - 解决无限循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27424975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com