Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
438 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...