Search code examples
javascriptjqueryhtmlcanvasfill

Fill a portion of drawn image in canvas


i drew an image using drawImage() api of html5 canvas. now i want to fill the white spaces of that drew image with different colors (individual box individual color). how can i do it? i am using html5 canvas and jquery.

i want to fill the white spaces with different color and those white spaces are not proper rectangular box.

thanks in advance.

enter image description here


Solution

  • [ changed answer after clarification from questioner ]

    Given: an image that has many fully-enclosed transparent areas.

    This is a method to fill each transparent area with a different color:

    1. Use context.getImageData to get an array of each canvas pixels [r,g,b,a] value.

    2. Loop thru the array and find the first transparent pixel (the "a" value ==0)

    3. Floodfill the entire transparent area containing that pixel with a new opaque color (replace the r,g,b values with your new color and replace the "a" value ==255).

    4. Repeat step#2 until all the transparent areas have been filled with new unique colors.

    To get you started...

    William Malone wrote a very nice article on how to get and use canvas's [r,g,b,a] color array.

    His article also shows you how to "floodfill" -- replace an existing color with a new color in an entire contiguous area.

    In your case, you would replace transparent pixels with a new color.

    This is his article:

    http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/

    [Addition to question: insert images into areas ]

    You need to make each colorized area transparent again—one at a time

    If you save each area's starting pixel from when you originally colorized the areas, you can start with that pixel and re-floodfill an area. This time you’ll set the alpha component of each pixel in that area to 0 (transparent).

    As each single area is transparent you use compositing to draw the new image only where the existing pixels are transparent. The composite you want is context.globalCompositeOperation=”source-out”.

    These examples show:

    • After uniquely colorizing each area.
    • After making 1 area transparent (the top-right area is transparent).
    • After compositing an image into the transparent area.

    enter image description hereenter image description hereenter image description here