Callum Linington
Callum Linington

Reputation: 14417

Alternative HTML5 Canvas Clear Method

The answer to this stackoverflow question effectively says to retrace the steps taken to draw a rectangle:

fillRect

by doing:

clearRect

First of all when I read this answer, I thought to just draw a white box the entire width and height of the canvas.

After thinking a bit more about how the Canvas element can save, and restore and the fact it implements a clearRect, does this mean that simply drawing another large rectangle could eat resources, if doing something like redrawing an entire bar graph every 100ms.

Originally drawing a bar graph every 100ms drew bars on top of each other, thus not being able to see the new bars because they're being layered.

But now, drawing a white rectangle as well, means that many rectangles are getting drawn, layered and it seems that the Canvas element tracks these?

Does this mean that it is possible to effectively overload the element, or overload the browser?

Upvotes: 2

Views: 619

Answers (2)

Winchestro
Winchestro

Reputation: 2188

the canvas does not track the drawing operations, but it tracks states. And the color values of individual pixels. If you draw a red rectangle you actually set the state to "draw red" and then set a rectangular shaped area of pixels to the currently drawn color (there are also different other drawing operations than just draw red on-top but I don't have experience with the so I can't tell you much other than that they exist)

For performance reasons you want to (among many other things) minimize

  • the amount of pixels you change
  • the amount of states you change

the difference between clearRect and width = width is that clearRect clears out the pixel data in the given area, while width = width clears out all pixel data and all states, like transformations, and styles. I think you already see the difference, there are a lot more things to consider (like Garbage Collection blocking your drawloop being one) but that would get a bit offtopic.

I'm not sure what you mean with overloading the browser. If you mean blocking and making the UI unresponsive then yes it's a thing that can and will happen since javascript is single-threaded and there are many ways you can accomplish it, but most likely not with such a reasonable operation :)

The worst thing you can do with drawing is make it super choppy on slow CPUs. Using requestAnimationFrame() instead of setTimeout()(which I assume you currently use because you mentioned 100ms) for your drawloop(s) is almost always a good and safe way to make sure your drawing will not block the UI.

Upvotes: 2

guest
guest

Reputation: 6698

the Canvas element tracks these [rectangles]

It doesn't track painting operations, as far as I know. (It's up to the implementation, but I don't know of any implementation that does.) You might be thinking of how it can save and restore things like transforms and paint colors.

Upvotes: 1

Related Questions