Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if something is drawn on canvas

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.

like image 889
Marvzz Avatar asked Jan 10 '11 07:01

Marvzz


People also ask

How do you check whether a canvas is empty or not?

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.

Which method can be used to draw lines rectangles circles and various shapes on a canvas?

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


1 Answers

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.

like image 191
gotohales Avatar answered Oct 17 '22 21:10

gotohales