如何检测通过画布生成的图像是否为空白(透明 PNG)?

2022-01-17 00:00:00 javascript html5-canvas

我正在开发一个应用程序,其中在 HTML5 画布上创建/编辑图像,然后将其保存到文件存储/云中.问题在于节约效率".在保存空白画布时,即使用 toDataURL() 发送完全透明的空白 PNG.检测空白 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.

但是,这种方法并非万无一失,因为用户可能会在单击绘图/编辑功能后保存图像,但不会绘制任何内容.是否有更原生的方法来检测画布是否返回自在浏览器上打开以来已更改的二进制字符串?或者其他方法来确保在客户端检测到空白透明 PNG?

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?

推荐答案

HTML:

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

脚本:

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;
}

更新:

不要为 CANVAS 使用像 border: 1px solid black; 这样的 CSS 样式声明,因为边框包含在画布图像中,因此 alpha chanel 总是不等于归零.

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.

相关文章