Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force HTML5 canvas to redraw while doing heavy JavaScript processing?

This question is related to this older one, but I wanted to be sure I had the right answer before I started making major changes to my code.

I'm working on a very computation-intensive JavaScript program that needs to constantly update an image in an HTML5 canvas to draw an animation. As written now, the code draws all the frames of the animation in a tight loop without returning control to the browser, meaning that what's ultimately displayed is just the final frame. I'm pretty sure the only way to fix this is to split the animation code into smaller pieces that can be called reentrantly through a timeout event. Is this correct? Or is there a way to force the canvas to display its contents at a certain point even in the middle of a tight JavaScript loop?

like image 920
templatetypedef Avatar asked May 16 '11 07:05

templatetypedef


People also ask

Why do we need to constantly clear and redraw the canvas to create an animation?

Because shapes on a canvas are just pixels, after we draw them there is no good way to move them (or remove them). The only way to update the canvas display is to clear it and redraw the scene. We may also have scrolled, which requires the background to be in a different position.

Is canvas more performant than Dom?

In short, the canvas and WebGL are more performant than the DOM, and with third-party libraries, its ease-of-use is comparable; furthermore, growing browser support for additional web standards have the potential to further boost canvas performance.

How do I reset my HTML canvas?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.


2 Answers

I'm pretty sure the only way to fix this is to split the animation code into smaller pieces that can be called reentrantly through a timeout event. Is this correct?

This is correct.

Javascript is single threaded, so there's no way for anything else to happen while your logic is being executed. Your only choice is to "emulate" threading by splitting your logic up in to micro-chunks to be executed on timeouts.

like image 132
funkybro Avatar answered Sep 28 '22 09:09

funkybro


You could use webworkers for this if they are available. Just calculate everything you need to do in the webworkers and post the result back when it's done. When you post the message back you can just refresh the image. Calculations will be done in the background and your page only blocks while updating the image.

like image 34
DoXicK Avatar answered Sep 28 '22 08:09

DoXicK