如何检查画布上是否绘制了某些内容

发布于 2024-10-11 01:53:59 字数 108 浏览 1 评论 0原文

如何检查画布上是否有数据或绘制的内容?

我有这个 元素,我想检查我的画布上是否绘制了某些内容。

How do I check if there is data or something drawn on a canvas?

I have this <canvas id="my-canvas"></canvas> element, and I want to check if my canvas has something drawn on it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

断念 2024-10-18 01:53:59

我发现的一个好方法是使用 toDataURL() 函数并将其与另一个空白画布进行比较。如果它们不同,那么您所比较的那个就具有某些内容。像这样的事情:

canvas = document.getElementById('editor');
ctx = canvas.getContext('2d');

canvas.addEventListener('mousemove',function(e){
    ctx.lineTo(e.pageX,e.pageY);
    ctx.stroke();
});

document.getElementById('save').addEventListener('click',function(){
    if(canvas.toDataURL() == document.getElementById('blank').toDataURL())
        alert('It is blank');
    else
        alert('Save it!');
});

这是一个 小提琴

我不能为此归功于我,我只是偶然发现了它,它修复了我的问题问题。也许这会在某个时候对某人有所帮助。

A good way I have found is to use the toDataURL() function and compare it with another, blank canvas. If they are different, than the one you are comparing it to has something on it. Something like this:

canvas = document.getElementById('editor');
ctx = canvas.getContext('2d');

canvas.addEventListener('mousemove',function(e){
    ctx.lineTo(e.pageX,e.pageY);
    ctx.stroke();
});

document.getElementById('save').addEventListener('click',function(){
    if(canvas.toDataURL() == document.getElementById('blank').toDataURL())
        alert('It is blank');
    else
        alert('Save it!');
});

Here is a fiddle

I can't take credit for this, I just stumbled upon it and it fixed my same issue. Maybe this will help somebody at some point.

在你怀里撒娇 2024-10-18 01:53:59

与检查每个像素相比,仅记录每次画布被填充或抚摸的时间可能会更有效。

一旦填充或描边发生,您就知​​道已经绘制了某些内容。

当然,“如何”是非常特定于应用程序的,因为我们首先不知道您的画布是如何绘制的。

Instead of checking every single pixel, it may be much more efficient to merely record every time the canvas gets filled or stroked.

Once a fill or stroke or has happened, then you know that something has been drawn.

Of course 'how' is very application specific, since we don't know how your canvas is getting drawn on in the first place.

天涯离梦残月幽梦 2024-10-18 01:53:59

到目前为止我还没有在 Stackoverflow 中看到过这种问题..但是有一个有趣的问题需要回答..

唯一的方法(我猜)是逐像素检查,即检查 R、G、B , A 每个像素,
如果这些值等于零,那么我们可以说该像素是空的..
这是我用来编写以下代码片段的技术。只需浏览一下

window.onload = function() {
  var canvas  = document.getElementById('canvas');
  if(!canvas.getContext) return;
  var ctx     = canvas.getContext('2d');
  var w       = canvas.width = canvas.height = 100;
  var drawn   = null;
  var d       = ctx.getImageData(0, 0, w, w); //image data 
  var len     = d.data.length;
  for(var i =0; i< len; i++) {
    if(!d.data[i]) {
      drawn = false;
    }else if(d.data[i]) {
      drawn = true;
      alert('Something drawn on Canvas');
      break;
    }
  }
  if(!drawn) {
    alert('Nothing drawn on canvas.. AKA, Canvas is Empty');
  }
}

在这里测试

I haven't seen this kind of question in Stackoverflow till now.. but an interesting One to answer..

The only way(I guess) is to check through pixel by pixel, i.e., check the R, G, B, A of each pixel,
if those values are equal to zero then we can say that the pixel is empty..
This is the technique I used to write the below code snippet.. just go through it

window.onload = function() {
  var canvas  = document.getElementById('canvas');
  if(!canvas.getContext) return;
  var ctx     = canvas.getContext('2d');
  var w       = canvas.width = canvas.height = 100;
  var drawn   = null;
  var d       = ctx.getImageData(0, 0, w, w); //image data 
  var len     = d.data.length;
  for(var i =0; i< len; i++) {
    if(!d.data[i]) {
      drawn = false;
    }else if(d.data[i]) {
      drawn = true;
      alert('Something drawn on Canvas');
      break;
    }
  }
  if(!drawn) {
    alert('Nothing drawn on canvas.. AKA, Canvas is Empty');
  }
}

Test it Here

九命猫 2024-10-18 01:53:59

以下是 Phrogz 的提示:https://stackoverflow.com/a/4649358

function eventOnDraw( ctx, eventName ){
  var fireEvent = function(){
    var evt = document.createEvent("Events");
    evt.initEvent(eventName, true, true);
    ctx.canvas.dispatchEvent( evt );
  }
  var stroke = ctx.stroke;
  ctx.stroke = function(){
    stroke.call(this);
    fireEvent();
  };
  var fillRect = ctx.fillRect;
  ctx.fillRect = function(x,y,w,h){
    fillRect.call(this,x,y,w,h);
    fireEvent();
  };
  var fill = ctx.fill;
  ctx.fill = function(){
    fill.call(this);
    fireEvent();
  };
}
...
var myContext = someCanvasElement.getContext('2d');
someCanvasElement.addEventListener( 'blargle', myHandler, false );
eventOnDraw( myContext, 'blargle' );

Here a tips from Phrogz : https://stackoverflow.com/a/4649358

function eventOnDraw( ctx, eventName ){
  var fireEvent = function(){
    var evt = document.createEvent("Events");
    evt.initEvent(eventName, true, true);
    ctx.canvas.dispatchEvent( evt );
  }
  var stroke = ctx.stroke;
  ctx.stroke = function(){
    stroke.call(this);
    fireEvent();
  };
  var fillRect = ctx.fillRect;
  ctx.fillRect = function(x,y,w,h){
    fillRect.call(this,x,y,w,h);
    fireEvent();
  };
  var fill = ctx.fill;
  ctx.fill = function(){
    fill.call(this);
    fireEvent();
  };
}
...
var myContext = someCanvasElement.getContext('2d');
someCanvasElement.addEventListener( 'blargle', myHandler, false );
eventOnDraw( myContext, 'blargle' );
笙痞 2024-10-18 01:53:59

嘿可能是一个迟到的答案,但我有点害怕需要额外的画布来进行比较。所以这是我的解决方案:

if (canvas.toJSON().objects.length === 0) {
    console.log('canvas is empty');
}

我希望这会有所帮助,您可以用它来执行一个功能,但该解决方案比我所看到的要干净得多。

Hey might be a late answer for this but I was kind of horrified to have the need of an extra canvas for comparing. So here is my solution:

if (canvas.toJSON().objects.length === 0) {
    console.log('canvas is empty');
}

I hope this helps, you can do a function with it but the solution is way cleaner than what I have seen around.

任性一次 2024-10-18 01:53:59

HTML 代码:

<canvas id='mainCanvas' style='border:solid'></canvas>
<canvas id='blankCanvas' style='display:none'></canvas>

JS 代码:

var mainCanvas= new SignaturePad(document.getElementById("mainCanvas"));
if (mainCanvas.toDataURL() == document.getElementById('blankCanvas').toDataURL()) {
                // Canvas is blank
}

注意:如果您为主画布提供高度和宽度,则同样的高度和宽度也适用于空白画布。

HTML Code:

<canvas id='mainCanvas' style='border:solid'></canvas>
<canvas id='blankCanvas' style='display:none'></canvas>

JS Code:

var mainCanvas= new SignaturePad(document.getElementById("mainCanvas"));
if (mainCanvas.toDataURL() == document.getElementById('blankCanvas').toDataURL()) {
                // Canvas is blank
}

Note: If your provide height and width to main canvas then same height and width to apply on blank canvas also.

飘然心甜 2024-10-18 01:53:59

要获取画布的像素,您必须使用 getImageData();方法-> getImageData() 参考

并检查 imageData 的每个像素是否为 0 或 255。

您的 ImageData 每个像素有 4 个单元格,rgba,您可以通过将计数增加 4 并查看每 4 个下一个数字来获取您的 rgba 值来访问每个像素。

您还可以获取空图像的 DataURL 并将画布的 DataURL 与它进行比较,看看它是否为空;)

To get the pixels of the canvas you have to use the getImageData(); method -> getImageData() reference

And to check if every pixels of your imageData are at 0 or 255.

Your ImageData will have 4 cells per pixels, r g b a and you cn access every pixels by incrementing your count by 4 and looking each 4 next numbers to hve your rgba value.

You can also get an empty image's DataURL and compare your canvas's DataURL to it to see if it's empty ;)

独﹏钓一江月 2024-10-18 01:53:59

我知道这可能是一个迟到的答案,但尝试这个解决方案:

西蒙萨里斯说:

与检查每个像素相比,仅记录每次画布被填充或描边的时间可能会更有效。

虽然这会更有效,但我确实设法找到一种方法来检测画布,通过检查每个像素来查看它是否被绘制/绘制。我尝试了一下,看看当画布为空和被绘制时像素数据会返回什么结果。我发现当画布为空时,所有像素数据在数组的所有索引位置都返回 0 。所以我用它来检测是否有任何0,结果我做了它,所以它返回一个布尔值。如果画布已绘制,则返回 true,如果尚未绘制,则返回 false

您可以在此处在 JSfiddle 代码上测试它

function isDrawnOn() {
            var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            var data = imageData.data;
            var result = null;
            var counter = 0;
            var last = data.length - 1;
            for (var i = 0; i < data.length; i++) {
                if (i === last && counter !== 0 && counter === last) {
                    result = false;
                    break;
                } else if (data[i] !== 0 && data[i] > 0) {
                    result = true;
                    break;
                } else {
                    counter++;
                    continue;
                }
            }
            return result;
        }

我希望这会有所帮助:)

I know it might be a late answer but try this solution:

Simon Sarris says that:

Instead of checking every single pixel, it may be much more efficient to merely record every time the canvas gets filled or stroked.

While that would be more efficient, however I did manage to find a way to detect the canvas to see if it is drawn/painted on by checking every pixel. I had a play around to see what results does the pixel data returns when the canvas is empty and when it is been painted on. I found out that when the canvas is empty all of the pixel data returns 0 in all index positions of the array. So I used that to detect if there is any 0's or not and as the result I made it so it returns a boolean. If the canvas has been drawn on then it returns true and if it hasn't then it returns false.

You can test it Here on JSfiddle

code:

function isDrawnOn() {
            var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            var data = imageData.data;
            var result = null;
            var counter = 0;
            var last = data.length - 1;
            for (var i = 0; i < data.length; i++) {
                if (i === last && counter !== 0 && counter === last) {
                    result = false;
                    break;
                } else if (data[i] !== 0 && data[i] > 0) {
                    result = true;
                    break;
                } else {
                    counter++;
                    continue;
                }
            }
            return result;
        }

I hope this helps :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文