如何检查画布是否为空

How to check if a canvas is blank?

本文关键字:是否 布是否 检查 何检查      更新时间:2023-09-26

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

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

更快:使用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);
}

正如@Kaiido所指出的,通过枚举像素的Uint32Array,而不是每个像素中的每个颜色通道,可以获得更好的性能。

// 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>