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.
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.
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.