Reputation: 2033
I was going through a tutorial demonstrating a basic io game here: https://victorzhou.com/blog/build-an-io-game-part-1/ and came across a question regarding rendering the whole canvas at every frame. Searching a bit more, it looks its advisable to redraw the whole canvas at every frame. I am trying to understand why to redraw the whole canvas always and not update only the shapes/area that we are interested in? Can someone please point out what is the best approach around this and what are the pros and cons of the same.
Also, if we need to have some particle like short animations, or any kind of animation with some randomness in it (example: fireworks.js), on a particular area, how can that be achieved when we render the whole frame?
Thanks.
Upvotes: 2
Views: 1313
Reputation: 54026
The canvas 2D API uses the GPU to render draw calls and these days you can count on every device having a GPU.
What GPUs excel at is writing pixels.
In high level languages like JavaScript a significant amount of CPU time needed to complete a call, like ctx.clearRect()
, is spent in the JS engine, vetting, casting arguments and prepping the call via the devices GPU interface.
Thus a call like...
ctx.clearRect(0, 0, 500, 500); // Example A
...will clear 250,000 pixels in 710µs(1) a rate of 352px per µs
But the same call...
ctx.clearRect(0, 0, 10, 10); // Example B
...will clear 100 pixels in 700µs, a rate of 0.17px per µs
A little quicker for the call, however if you compare the pixel rates, example A is a clear winner.
To highlight how JS can slow things down, the next clear uses strings (people do this)
ctx.clearRect("0","0", "10", "10"); // Example C
... and takes 1300µs. A rate of about 0.08px per µs. That is 4400 times slower at changing pixels than example A.
In JS the general rule is to reduce the number of draw calls and have each call change as many pixels as possible
(1) µs = 1/1,000,000 seconds
Upvotes: 1
Reputation: 1631
Strictly speaking you can, "patch" the canvas without clearing it, but in your case I'm not sure it's what you want.
here is are some great articles on the matter https://www.html5rocks.com/en/tutorials/canvas/performance/ and https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations
Upvotes: 1