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

后端 未结 2 1082
一生所求
一生所求 2021-02-05 16:00

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 sav

相关标签:
2条回答
  • 2021-02-05 16:20

    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.

    0 讨论(0)
  • 2021-02-05 16:29

    This isn't native, but this should work, because a blank canvas always generates the same data URL.

    So, you could create a hidden canvas, get that canvas's data URL and if it matches that of your editor, then don't upload it. Simple as that.

    Demo. First, go hit save without going over the canvas. Then go over it and then hit save. Tada!

    0 讨论(0)
提交回复
热议问题