Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect how much of a canvas element is filled in HTML5

I just started with HTML5, and I have a paint program where a user can fill in the canvas by clicking the mouse button and dragging the cursor around like a pen. I want to be able to figure out what percentage of the canvas is currently filled with the pen. How could I do this? Here's my current code on Gist Thanks!

like image 555
Ian Hyzy Avatar asked Oct 07 '22 12:10

Ian Hyzy


1 Answers

You can get all the raw pixel values of the <canvas> using getImageData() call

https://developer.mozilla.org/en-US/docs/DOM/CanvasRenderingContext2D#getImageData%28%29

Then you loop through this pixel data in a Javascript loop and count all pixels which are not of the background color.

The percent of filled in canvas is

 completed = filledInPixels / (canvas.width * canvas.height)

Note that getImageData() call is extremely slow and you might want to call it only like once in a second.

like image 112
Mikko Ohtamaa Avatar answered Oct 10 '22 02:10

Mikko Ohtamaa