Canvas How to - Check if canvas is blank








Question

We would like to know how to check if canvas is blank.

Answer


<!--from w ww.  j  ava  2 s  .  c  o  m-->


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    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())
            console.log('It is blank');
        else
            console.log('Save it!');
    });
}//]]>  
</script>
</head>
<body>
   <canvas id='editor' style='border:solid'></canvas>
   <canvas id='blank' style='display:none'></canvas>
   <button id='save'>Save</button>
</body>
</html>

The code above is rendered as follows: