Fabric JS 逐像素操作

gol*_*nge 6 javascript fabricjs

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

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

还有其他想法吗?

编辑:

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

我使用覆盖图像作为外部 png 文件。

mar*_*rkE 5

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

您必须将覆盖图像绘制到 html5 画布上,并用于getImageData从该画布中获取像素数据。

getImageData().data包含画布上每个像素的红色、绿色、蓝色和 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});
}
Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; }
#canvas{border:1px solid red;}
Run Code Online (Sandbox Code Playgroud)
<h4>The bounding box of the transparent rectangle is stroked in red</h4>
<canvas id="canvas" width=300 height=300></canvas>
Run Code Online (Sandbox Code Playgroud)