Search code examples
javascripthtmlcanvashtml5-canvas

Check whether canvas is black


I have a script which takes a picture and creates black and white R, G and B channels. And I would like to count how many channels have something on them (black = no colour, white = colour data).

It works by going through every single pixel and saving data in 3 different canvas elements. Each one showing different channel.

It works great but when I give a Red and Blue picture only, the green channel (obviously) is completely black.

So my question is, how do I check whether the canvas is completely black? I would like to avoid looping through every pixel in every channel to see if it's all black.

cheers


Solution

  • Ok I've tested a few things and the easiest solution I could come up with was creating a 1x1 offscreen canvas, then drawing either your image or your original canvas you want to check for data on it, scaled down to 1 pixel and check it (I also added basic caching).

    It's not a precise check, and the result depends on how the pixel data is distributed in the original image, so as GameAlchemist noted, you may loop through all the pixels anyway if the result of the check is 0 if you want accurate results.

    function quickCheck(img){
        var i = arguments.callee; //caching the canvas&context in the function
        if(!i.canvas){i.canvas = document.createElement("canvas")} 
        if(!i.ctx)   {i.ctx    = i.canvas.getContext("2d")}
    
        i.canvas.width=i.canvas.height = 1;
        i.ctx.drawImage(img,0,0,1,1);
        var result = i.ctx.getImageData(0,0,1,1);
        return result.data[0]+result.data[1]+result.data[2]+result.data[3];
    }