fabricjs - Fabric JS 中自定义图像的描边

标签 fabricjs stroke

我正在尝试在使用 Fabric JS 添加到 Canvas 的图像周围创建笔划。我添加到具有透明背景的 PNG 中的笔画如下所示:

enter image description here

尽管我试图在图像“周围”创建笔划并将笔划粘贴到图像的边缘,但 Fabric JS 只是创建了一个“方形”笔划。

我怎样才能完成“围绕”图像的描边,有什么想法吗? 我似乎找不到任何文档或演示来完成我正在尝试做的事情。

谢谢

最佳答案

只需几步即可完成。

  1. 将 png 图像上传到 Canvas
  2. 添加“贴纸描边效果”(来自this article)
      // this._ctx = context of canvas
      this._ctx.shadowColor = '#fff';
      this._ctx.shadowBlur = 3;
      this._ctx.shadowOffsetX = 0;
      this._ctx.shadowOffsetY = 0;
      this._ctx.drawImage(img, 30, 30, img.width, img.height);

      // get contents of blurry bordered image
      const imgData = this._ctx.getImageData(
        0,
        0,
        this._ctx.canvas.width - 1,
        this._ctx.canvas.height - 1
      );

      const opaqueAlpha = 255;

      // turn all non-transparent pixels to full opacity
      for (let i = imgData.data.length; i > 0; i -= 4) {
        if (imgData.data[i + 3] > 0) {
          imgData.data[i + 3] = opaqueAlpha;
        }
      }

      // write transformed opaque pixels back to image
      this._ctx.putImageData(imgData, 0, 0);

      this._ctx.shadowColor = '#aaa';
      this._ctx.shadowBlur = 3;
      this._ctx.shadowOffsetX = 0;
      this._ctx.shadowOffsetY = 0;
      this._ctx.drawImage(this._canvas, 0, 0);
  1. 将数据导出到 base64 并通过 fabric 粘贴
      // you can export your image to data url
      const url = this._canvas.toDataURL();

      // and you can add image from data url to fabric
      fabric.Image.fromURL(url, oImg => {
        this._cf.add(oImg);
      });

它会工作,但为了更好的用户体验,你应该考虑如何动态地做(我现在正在研究),我的意思是:用户添加图像,你想让他选择“中风” “或者不等等等等......

关于fabricjs - Fabric JS 中自定义图像的描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264312/

相关文章:

javascript - 如何在fabric.js中根据下 Canvas 调整上 Canvas 的大小?

c# - 在 WPF 中的行的开头和结尾放置一个形状

html - 在所有浏览器中实现纯文本轮廓/描边的最佳方式?

r - 添加笔画点的图例ggplot2

fabricjs - 在 fabricjs 中缩放一组对象时防止翻转

reactjs - Fabricjs 无法在 'texImage2D' : The image element contains cross-origin data, 上执行 'WebGLRenderingContext',可能无法加载

javascript - 无法在 Canvas (fabric.js) 的裁剪区域之外查看选择器控件

javascript - Fabric.js 中的 Canvas 坐标有偏移

ios - Swift:来自中心的 UIBezierPath 描边动画

ios - iOS Core Graphics 中的 "shape burst"描边