How to check if a canvas is empty or blank

This example shows you how to check whether a Canvas is blank or not using JavaScript.

JavaScript Function:

function isCanvasEmpty(cnv) { const blank = document.createElement('canvas'); blank.width = cnv.width; blank.height = cnv.height; return cnv.toDataURL() === blank.toDataURL(); }

Example:

JavaScript Function:

<!DOCTYPE html> <html> <head> </head> <body> <div> <div> <canvas id='cnvinput' style='border:solid'></canvas> </div> <div style="padding-top:20px;"> <input type="button" id="btnstartdraw" value="Start Draw" onclick="startdraw();" /> <input type="button" id="btnVerify" value="Verify Canvas" onclick="checkvanvs();" /> </div> <script type="text/javascript"> var canvas; var ctx; function startdraw() { canvas = document.getElementById('cnvinput'); ctx = canvas.getContext('2d'); canvas.addEventListener('mousemove', function (e) { ctx.lineTo(e.pageX - canvas.parentElement.offsetLeft, e.pageY - canvas.parentElement.offsetTop); ctx.stroke(); }); } function checkvanvs() { var cnv = document.getElementById('cnvinput'); if (isCanvasEmpty(cnv)) alert('Empty!'); else alert('Not Empty!!'); }; function isCanvasEmpty(cnv) { const blank = document.createElement('canvas'); blank.width = cnv.width; blank.height = cnv.height; return cnv.toDataURL() === blank.toDataURL(); } </script> </div> </body> </html>