如果HTML5画布为空白或有彩色像素,我该如何检查。有快速的方法吗?
<canvas width="200" height="200"></canvas>
答案 0 :(得分:48)
更快:使用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);
}
较慢:使用空白画布比较数据网址
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>