How to check if something is drawn on canvas
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.
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.
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
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.