window.requestAnimationFrame冻结浏览器窗口

时间:2019-02-23 21:07:36

标签: javascript

我正在尝试使用Canvas通过以下代码在JS中制作动画,但是window.requestAnimationFrame运行会告诉它冻结浏览器窗口:

const renders = function(){
    //resize
document.getElementById('maingame').width = window.innerWidth
document.getElementById('maingame').height = window.innerHeight
document.getElementById('maingame').style.width = window.innerWidth + 'px'
document.getElementById('maingame').style.height = window.innerHeight + 'px'
    //resize
    gr.clearRect(0,0,2000,2000) //clears
    
    //draws main c (Isolate)
    gr.save()
    gr.translate(window.innerWidth/2,window.innerHeight/2)
    gr.rotate(d)
    gr.drawImage(main0,-(main0.width*size)/2,-(main0.height*size)/2,main0.width*size,main0.height*size)
    gr.restore();
    camx = lerp(camx,x,0.1)
    camy = lerp(camy,y,0.1);
    gr.translate(x,y)//moves the camera
gr.drawImage(img4, 90+x, 130+y,img4.width*0.2,img4.height*0.2)
   for(let i = 0; i < things.length; i++){
    gr.drawImage(img3,things[i].x,things[i].y,img3.width*0.2,img3.height*0.2)

    window.requestAnimationFrame(renders); //recalls image to be drawn again asap
   }
   
};

// Game Start
window.requestAnimationFrame(renders)

我正在尝试为使用HTML 5渲染游戏图形的引擎构建基础,但是我无法使它正常工作...(是的,我对Phaser有所了解),有人知道为什么它会保持冻结吗?< / p>

1 个答案:

答案 0 :(得分:0)

请求的位置错误。您只想在渲染后请求一个动画帧。

for(let i = 0; i < things.length; i++){
    gr.drawImage(img3,things[i].x,things[i].y,img3.width*0.2,img3.height*0.2)
} // move this curly brace up !!!!
window.requestAnimationFrame(renders); // for next render