How to check if a canvas is blank? [duplicate]

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>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)