Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.requestAnimationFrame freezes browser window

Tags:

javascript

I'm trying to animate in JS using Canvas with the following code but the window.requestAnimationFrame runs tell it freezes the browser window:

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)

I'm trying to build the basics for a engine to render game graphics in HTML 5 but I can't get this to work... (yes I know about phaser), does anyone know why it keeps freezes?

like image 889
Andrew Hansen Avatar asked Oct 22 '25 12:10

Andrew Hansen


1 Answers

The request is in the wrong spot. You only want to request one animation frame after rendering.

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
like image 116
traktor Avatar answered Oct 25 '25 03:10

traktor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!