0
\$\begingroup\$

I have a game loop like so:

setInterval(function()  
{  
    context.save();  
    context.rect(26, 144, 745, 400);  
    context.clip();  
    context.drawImage(myImage, 100, 100, 900, 900);  
    context.restore();  
}, 40);

As it runs the canvas gradually slows down to a stop. If I put the drawImage outside of the clipping then it runs indefinitely at the correct speed. Is there something I'm doing wrong?

\$\endgroup\$
6
\$\begingroup\$

Using setInterval with such a low interval period means that the drawing is probably being queued up before the previous function has finished calling (for example, the drawing takes 50ms and your interval is 40ms, then it will always be trying to catch up).

I would recommend using requestAnimationFrame, a polyfill example can be found here. Here's a simple example:

window.requestAnimationFrame(function(){
    context.save();
    context.rect(26, 144, 745, 400);
    context.clip();
    context.drawImage(myImage, 100, 100, 900, 900);
    context.restore();
});

If you cannot, for some reason, use that you should do a timeout rather than an interval, and only restart the timer after your scene drawing have been completed.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .