javascripthtml5-canvas

How to detect if an image generated via canvas is blank (transparent PNG)?


I am working on an application in which an image is created/edited on a HTML5 canvas and then saved into a file-store/cloud. The problem is that of "saving efficiency". On save of a blank canvas, i.e. a totally transparent blank PNG is sent with toDataURL(). One way of detecting a blank PNG is by switching a boolean value upon click of any editing/drawing functionality and reseting that value upon clear-screen.

However, such a method is not foolproof because a user may save the image after clicking a draw/edit function and yet not draw anything. Is there a more native approach to detect if the canvas returns a binary string that has changed since opening up on the browser? Or some other way to ensure that a blank transparent PNG is detected at client side?


Solution

  • HTML:

    <canvas id="canvas_img" width="300" height="200" border="0"></canvas>
    

    SCRIPT:

    isCanvasTransparent(document.getElementById("canvas_img"));
    
    function isCanvasTransparent(canvas) { // true if all pixels Alpha equals to zero
      var ctx=canvas.getContext("2d");
      var imageData=ctx.getImageData(0,0,canvas.offsetWidth,canvas.offsetHeight);
      for(var i=0;i<imageData.data.length;i+=4)
        if(imageData.data[i+3]!==0)return false;
      return true;
    }
    

    UPDATE:

    Dont use CSS style declarations like border: 1px solid black; for CANVAS, because border included into canvas image, and, as result, alpha chanel is always not equals to zero.