Search code examples
html5-canvasgetimagedata

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!


Solution

  • 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.