36

如何检查 HTML5 画布是否为空白或有彩色像素。有没有快速的方法?

<canvas width="200" height="200"></canvas>
4

1 回答 1

79

更快:context.getImageData()用于查找“彩色”像素(非零值)

// 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);
}

正如@KaiidoUint32Array指出的那样,您可以通过枚举一个像素而不是每个像素中的每个颜色通道来获得更好的性能。

// 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);
}

较慢:将数据 URL 与空白画布进行比较

function isCanvasBlank(canvas) {
  const blank = document.createElement('canvas');

  blank.width = canvas.width;
  blank.height = canvas.height;

  return canvas.toDataURL() === blank.toDataURL();
}

基准

演示

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>

于 2013-06-30T03:19:08.070 回答