Search code examples
javascriptjquerycanvashtml5-canvasfabricjs

How to detect empty areas on canvas in FabricJS?


I need to check is there any empty areas on canvas in FabricJS and display alert. I think this can be done by detecting pixels on canvas but I have no idea. How to do that?


Solution

  • To get pixeldata you need access to the 2D context. To do that in FabricJS you have to call StaticCanvas.getContext(); the standard fabric canvas will have this in the prototype chain.Fabric StaticCanvas doc

    From there to get the pixel data use

    var ctx = yourCanvas.getContext(); // your canvas is the Fabric canvas
    var pixelData = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height);
    

    To access a single pixel you have to calculate the index and then retrieve the 4 bytes that make a pixel, one byte each for red, green, blue, and alpha.

    Function to get a pixel once you have the pixelData.

    // pixelData is the pixel data, x and y are the pixel location
    function getPixel(pixelData,x,y){
        // make sure the coordinate is in bounds
        if(x < 0 || x >= pixelData.width || y < 0 || y >= pixelData.height){
             return {
                r : 0,
                g : 0,
                b : 0,
                a : 0 
             };
       }
       // get the index of the pixel. Floor the x and y just in case they are not ints
       var index = Math.floor(x) * 4 + Math.floor(y) * 4 * pixelData.width;
       // return the pixel data
       return {
           r : pixelData.data[index++],
           g : pixelData.data[index++],
           b : pixelData.data[index++],
           a : pixelData.data[index++] 
       };
    }
    

    That should help you find the empty areas. Note that when alpha is zero, red, green, and blue will also be zero. The function above is very slow so it is not intended for use in your problem, it just shows how to get a pixel from the pixelData and how to get a pixel address (index).