简体   繁体   English

Fabric.js 创建动态图像遮罩

[英]Fabric.js create dynamic image mask

I want to mask the original image using alpha mask imag e.我想使用alpha 蒙版图像 e 蒙版原始图像。 I can do alpha masking on image with the following code.我可以使用以下代码对图像进行 alpha 遮罩。 But I want to be able to edit the mask with the brush, how can I do that?但我希望能够用画笔编辑蒙版,我该怎么做?

In theory if I paint the mask white it should be opaque, if I paint it black it should be transparent.理论上,如果我把面具涂成白色,它应该是不透明的,如果我把它涂成黑色,它应该是透明的。

The code I tried:我试过的代码:

 window.onload = function () { var img = document.getElementById("mask"); var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); var idata = ctx.getImageData(0, 0, canvas.width, canvas.height); var data32 = new Uint32Array(idata.data.buffer); var i = 0, len = data32.length; while (i < len) data32[i] = data32[i++] << 8; ctx.putImageData(idata, 0, 0); ctx.globalCompositeOperation = "source-in"; const defaultImg = document.getElementById('img'); ctx.drawImage(defaultImg, 0, 0); };
 .container { text-align: center; }
 <div class="container"> <p>Default Image </p> <img id="img" crossorigin="anonymous" src="https://i.ibb.co/FhgZgzN/cat.png"> <p>Mask </p> <img id="mask" crossorigin="anonymous" src="https://i.ibb.co/NswxsLc/cat-mask.png"> <p>Result </p>: <canvas id="canvas"></canvas> </div>

You can use FabricJS to enable mask drawing.您可以使用 FabricJS 启用蒙版绘制。 I've done this in the MockoFun graphic designer .我已经在MockoFun 平面设计师中完成了这项工作。

There's a discussion on Github about this: https://github.com/fabricjs/fabric.js/issues/6465#issuecomment-1127690007 Github上有一个关于这个的讨论: https ://github.com/fabricjs/fabric.js/issues/6465#issuecomment-1127690007

Create a new brush that extends the PencilBrush ( https://github.com/fabricjs/fabric.js/blob/master/src/brushes/pencil_brush.class.js )创建一个扩展 PencilBrush 的新画笔( https://github.com/fabricjs/fabric.js/blob/master/src/brushes/pencil_brush.class.js

Add 2 options for this brush:为这个画笔添加 2 个选项:

  • targetMaskFilter - to store the reference to the BlendImage filter targetMaskFilter - 存储对 BlendImage 过滤器的引用
  • mode that is source-over or destination-over to remove/add from the mask image从掩码图像中删除/添加的source-overdestination-over模式

The idea is to draw on the mask layer using the brush and then combining the mask with the original image using the BlendImage filter.这个想法是使用画笔在蒙版图层上绘制,然后使用 BlendImage 过滤器将蒙版与原始图像组合。

Here's a Gist showing my implementation: https://gist.github.com/codingdudecom/ba183221d705a23962fcfcd3cae0c63f这是显示我的实现的要点: https ://gist.github.com/codingdudecom/ba183221d705a23962fcfcd3cae0c63f

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

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