Fabric JS 逐像素操作

Fabric JS pixel by pixel manipulation

我有带矩形透明孔的叠加图像。下面是可缩放和可拖动的图像。如何只剪切图像的可见部分?

如何确定透明矩形的大小和位置?是否可以仅在叠加图像上逐像素进行 alpha 通道搜索?

还有其他想法吗?

编辑:

另一个引用问题的解决方案很有用,尽管它仅适用于整体 canvas 而不适用于背景、叠加层或添加的图像或形状等个别项目。是否可以读取单个织物元素的像素值?

我使用叠加图像作为外部 png 文件。

FabricJS API 不包含获取图像像素值的方法。

您必须将叠加图像绘制到 html5 canvas 上,然后使用 getImageData 从 canvas 中获取像素数据。

getImageData().data 包含 canvas 上每个像素的红色、绿色、蓝色和 alpha 信息。

您可以测试每个像素的 alpha 值并确定透明矩形的最小和最大边界。

下面是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="http://masterblocks.co.in/static/img/logo.png";
function start(){
  cw=canvas.width=img.width;
  ch=canvas.height=img.height
  ctx.drawImage(img,0,0);
  // clear a test rectangle
  ctx.clearRect(100,100,100,75);
  // get clear rect bounds
  var bounds=findCutoutBounds();
  // test: stroke the bounds
  ctx.lineWidth=2;
  ctx.strokeStyle='red';
  ctx.strokeRect(bounds.x,bounds.y,bounds.width,bounds.height);
}

// Get the imageData of that canvas
function findCutoutBounds(){
  var minX=1000000;
  var minY=1000000;
  var maxX=-1;
  var maxY=-1;
  var data=ctx.getImageData(0,0,canvas.width,canvas.height).data;
  for(var y=0;y<ch;y++){
    for(var x=0;x<cw;x++){
      var n=(y*cw+x)*4;
      if(data[n+3]<5){
        if(y<minY){minY=y;}
        if(y>maxY){maxY=y;}
        if(x<minX){minX=x;}
        if(x>maxX){maxX=x;}
      }
    }}
  return({x:minX,y:minY,width:maxX-minX,height:maxY-minY});
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>The bounding box of the transparent rectangle is stroked in red</h4>
<canvas id="canvas" width=300 height=300></canvas>