如何检测通过画布生成的图像是否为空白(透明PNG)? [英] How to detect if an image generated via canvas is blank (transparent PNG)?

查看:181
本文介绍了如何检测通过画布生成的图像是否为空白(透明PNG)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,在该应用程序中,在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;
}

更新

不要使用CSS样式声明,如 border:1px solid black; 表示 CANVAS ,因为边框包含在画布图像中,因此,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.

这篇关于如何检测通过画布生成的图像是否为空白(透明PNG)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆