Reputation: 149
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?
Upvotes: 4
Views: 1367
Reputation: 19301
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
Upvotes: 4