繁体   English   中英

Fabric JS 逐像素操作

[英]Fabric JS pixel by pixel manipulation

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

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

还有其他想法吗?

编辑:

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

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

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}); }
 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM