The interesting thing about Canvas is we can have more than one Canvas and even we can create Canvas dynamically through javascript. Why would we need more than one Canvas !?! There may be many answers to this, but the most important of all is, I think, when we need to update the Canvas. If you remember we have made an animation in our previous tutorial. And diving a little inside of that code will show you that we are redrawing it on each timer event.
The whole idea of animating in Canvas revolves around updating the Canvas on each timer event. But we also know that once something is written/drawn in Canvas
we can not have a reference to it. So in the other hand we have to re-write or re-draw everything again. And this redrawing over and again will take us to a performance problem. Re-drawing the whole canvas with all the elements, again and again is not a good idea and we must avoid it if we can. The best thing to do is to separate elements to different Canvases. And we will never update the Canvas which contains the elements we do not need to be changed. Then only refresh the Canvases whose content needs updating upon timer event. Seems like a plan ? I have done this with the example source code, for your reference.
The source code of the example, contains two canvases and I am updating only the second Canvas as it needs updating.
Point to note here is Canvas refresh does not mean only updating the values, but actually it means erase everything from the Canvas and re-draw everything with the updated value.
Hope that helps to understand the power of Canvas a little better.
Hi Saumya, your post is a little misleading. When you say “dynamically create” canvas objects, I am connecting that to dynamically creating objects in C++ or Java. Where a variable # of elements can be created by the program.
its the same thing. You can dynamically create a canvas (like another object) with “new” keyword.