Vivek Pradhan
Vivek Pradhan

Reputation: 4847

When to clear a canvas when redrawing images

I am working on a web app that does some face detection from webcam. I am using WebRTC and I use the ctx.drawImage() method to draw the video element into the canvas.

On top of this image I draw a rectangle to outline the face. I repeat this 15 times if the webcam fps is 15. But I don't clear the canvas anywhere. I don't see any lag after a couple of minutes of streaming the webcam content into the canvas and doing the face detection.

I tried using the memory profiler in chrome devtools to see if there are some alarming spikes. I am a little worried because there is NOT anything fishy going on there. But there should be a spike right? I mean, I redraw an image on the canvas, every couple of milliseconds. Does that not mean, I'd have layers of each frame and a rectangle stacked on top of another. There will be 15 such layers in a second! This sounds pretty alarming to me.

I want to understand, how should I debug the canvas profiling feature. I realised it got removed after Chrome 44. Also, anyone gone through the same situation, what's the best way of showing every frame then. Should I not have to clear the canvas after every frame? If I should clear it, what's the best way of doing that. I hope I could explain my problem here.

Edit

  1. For someone wanting to see this in action. I have put together a simple fiddle to demonstrate clearRect as suggested by @touko. Uncomment the last line, and it clears it totally. NO layers.

Upvotes: 2

Views: 832

Answers (1)

touko
touko

Reputation: 2047

Every time you draw something on the canvas it overrides the current information in that location -> one canvas will never have multiple 'layers' on it.

Eg. you have to call clearRect, which essentially writes new data to the canvas, to 'clear' the canvas

Upvotes: 1

Related Questions