Javascript 如何检查画布图像是纯黑色还是纯白色

Javascript 如何检查画布图像是纯黑色还是纯白色,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,如何通过JavaScript测试画布图像是否为纯黑色或白色,而不通过每个像素进行循环?有解决方案吗?基本上,这个解决方案通过计算所有像素的rgba和来“检查”每个像素。但这不是手动检查: // getting image data of canvas imgData = canvasRenderingContext.getImageData(0, 0, canvas.width, canvas.height); // get sum of r+g+b+a of all pixels let s

如何通过JavaScript测试画布图像是否为纯黑色或白色,而不通过每个像素进行循环?有解决方案吗?

基本上,这个解决方案通过计算所有像素的rgba和来“检查”每个像素。但这不是手动检查:

// getting image data of canvas
imgData = canvasRenderingContext.getImageData(0, 0, canvas.width, canvas.height);

// get sum of r+g+b+a of all pixels
let sum = imgData.data.reduce(function(a, b){return a + b;}, 0);

// if sum is zero => Black, else if sum is the multiplication of pixel amount and 765 (3*255) it is pure white.
console.log(sum > 0 ? (sum >= canvas.width*canvas.height*765 ? "Canvas is pure white." : "Canvas is not pure black or white") : "Canvas is pure black.");

可能是相关帖子:。在引擎盖下,它肯定是O(n)像素,但你不必自己写一个循环。做一个求和运算将花费比使用.some()或.every()进行逻辑检查更多的运算。就性能而言,它没有那么好。