在Fabric JS中描画自定义图像

时间:2019-05-22 20:12:32

标签: fabricjs stroke

我正在尝试使用Fabric JS在添加到画布的图像周围创建笔触。我添加到具有透明背景的PNG中的笔画看起来像这样:

enter image description here

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

如何在图像周围“完成笔画”,有什么想法? 我似乎找不到任何文档或演示来完成我想做的事情。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过几个步骤进行操作。

  1. 将png图像上传到画布
  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并将其粘贴到结构
      // 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);
      });

它可以工作,但是为了获得更好的用户体验,您应该考虑如何动态地进行操作(我现在正在研究它),我的意思是:用户添加图像,您希望给他“中风”选项“还是不,等等。