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.
we use the toDataURL() function to check whether two canvas is the same or not. and also we check using SignaturePad to signaturePad. isEmpty() function.
The most basic path you can draw on canvas is a straight line. The most essential methods used for this purpose are moveTo() , lineTo() and the stroke() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With