How can I check, if a HTML5 canvas is blank or has colored pixels. Is there a fast method?
<canvas width="200" height="200"></canvas>
I found out that when the canvas is empty all of the pixel data returns 0 in all index positions of the array. So I used that to detect if there is any 0 's or not and as the result I made it so it returns a boolean. If the canvas has been drawn on then it returns true and if it hasn't then it returns false .
Faster: Using context.getImageData()
to find "colored" pixels (non-zero values)
// returns true if all color channels in each pixel are 0 (or "blank") function isCanvasBlank(canvas) { return !canvas.getContext('2d') .getImageData(0, 0, canvas.width, canvas.height).data .some(channel => channel !== 0); }
As @Kaiido points out, you can get even better performance by enumerating over a Uint32Array
of pixels instead of each color channel in every pixel.
// returns true if every pixel's uint32 representation is 0 (or "blank") function isCanvasBlank(canvas) { const context = canvas.getContext('2d'); const pixelBuffer = new Uint32Array( context.getImageData(0, 0, canvas.width, canvas.height).data.buffer ); return !pixelBuffer.some(color => color !== 0); }
Slower: Comparing data URLs with a blank canvas
function isCanvasBlank(canvas) { const blank = document.createElement('canvas'); blank.width = canvas.width; blank.height = canvas.height; return canvas.toDataURL() === blank.toDataURL(); }
Benchmark
Demo
document.getElementById('check').addEventListener('click', function() { const blank = isCanvasBlank(document.getElementById('canvas')); alert(blank ? 'blank' : 'not blank'); }); document.getElementById('draw').addEventListener('click', function() { drawOnCanvas(document.getElementById('canvas')); }); document.getElementById('clear').addEventListener('click', function() { const canvas = document.getElementById('canvas'); canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); }); function isCanvasBlank(canvas) { const context = canvas.getContext('2d'); const pixelBuffer = new Uint32Array( context.getImageData(0, 0, canvas.width, canvas.height).data.buffer ); return !pixelBuffer.some(color => color !== 0); } function drawOnCanvas(canvas) { const context = canvas.getContext('2d'); context.fillStyle = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16); context.fillRect(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height), Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); }
canvas { display: block; margin-top: 10px; border: 1px solid black; }
<button id="check"> Check </button> <button id="draw"> Draw </button> <button id="clear"> Clear </button> <canvas id="canvas" width="200" height="200"></canvas>
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