Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 画布仅获取不透明像素_Javascript_Html_Canvas - Fatal编程技术网

Javascript 画布仅获取不透明像素

Javascript 画布仅获取不透明像素,javascript,html,canvas,Javascript,Html,Canvas,如何在图像画布上计算区域的透明像素,我编写了这个函数,但我想有另一种方法 ctx = getCanvasImg(); for (var x = selection.x2 * zoom; x > selection.x1 * zoom; x--) { for (var y = selection.y2 * zoom; y > selection.y1 * zoom; y--) { var pixel = ctx.getImageData(x, y, 1, 1);

如何在图像画布上计算区域的透明像素,我编写了这个函数,但我想有另一种方法

ctx = getCanvasImg();
for (var x = selection.x2 * zoom; x > selection.x1 * zoom; x--) {
    for (var y = selection.y2 * zoom; y > selection.y1 * zoom; y--) {
        var pixel = ctx.getImageData(x, y, 1, 1);
        var data = pixel.data;
        var rgba = 'rgba(' + data[0] + ',' + data[1] + ',' + data[2] + ',' + (data[3] / 255) + ')';
        if (data[0] == 0) {
            countWhite++;
        }
    }
}

只需抓住需要的区域一次:

var idata = ctx.getImageData(startX, startY, widthOfArea, heightOfArea);
要计算所有不透明像素,可以使用UINT32阵列进行迭代:

如果是big-endian,则使用And掩码而不是位移位来检查此方法:

// big-endian byte order
for(var i = 0, len = data.length, count = 0; i < len;) {
  if (data[i++] & 0xff === 255) count++;  // masks RRGGBBAA to 000000AA, then =255?
}

您可以始终使用DataView并指定endianess,但是在这种情况下,由于开销较小,因此没有任何好处。

只需抓住需要的区域一次:

var idata = ctx.getImageData(startX, startY, widthOfArea, heightOfArea);
要计算所有不透明像素,可以使用UINT32阵列进行迭代:

如果是big-endian,则使用And掩码而不是位移位来检查此方法:

// big-endian byte order
for(var i = 0, len = data.length, count = 0; i < len;) {
  if (data[i++] & 0xff === 255) count++;  // masks RRGGBBAA to 000000AA, then =255?
}

您可以始终使用DataView并指定endianess,但是在这种情况下,由于开销较小,因此没有任何好处。

您的解决方案有问题吗?您的解决方案有问题吗?