Determine how many canvas elements are filled in HTML5

I just started with HTML5, and I have a drawing program where the user can fill the canvas by clicking the mouse button and dragging the cursor like a pen. I want to know what percentage of the canvas is filled with a pen. How can i do this? Here is my current Gist code Thank you!

+4
source share
1 answer

You can get all raw <canvas> pixel values ​​by calling getImageData ()

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

Then you look at that pixel data in a Javascript loop and count all the pixels that don't have a background color.

Percentage of Canvas Filled

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

Note that the call to getImageData() very slow, and you can only call it just in a second.

+4
source

Source: https://habr.com/ru/post/1436726/


All Articles