fabric.js 钢笔橡皮问题

这篇博客主要讨论了使用fabric.js库在前端开发中遇到的钢笔和橡皮工具的问题。作者详细介绍了如何实现钢笔和橡皮的绘制,包括使用rgba颜色来实现透明效果。在还原绘制时,作者发现钢笔和橡皮的数据结构相似,可以通过调整数据属性进行还原。在实现过程中,遇到了对象属性更新和渲染不全的挑战,通过避免使用fabric.js的内置属性设置和删除特定的group属性解决了这些问题。

1.钢笔橡皮绘制
钢笔

this.fabricObj.freeDrawingBrush = new fabric.PencilBrush( this.fabricObj );        //钢笔刷
this.fabricObj.freeDrawingBrush.width = this.lineWidth;    //线宽
this.fabricObj.isDrawingMode = true;     //自由绘制

橡皮

 this.fabricObj.freeDrawingBrush = new fabric.EraserBrush( this.fabricObj);
 this.fabricObj.freeDrawingBrush.width = this.lineWidth;
 this.fabricObj.isDrawingMode = true;

透明色
this.fabricObj.freeDrawingBrush自身无opacity属性,但是color属性可以用rgba属性,将hex转为rgba

 hexToRgba(hex, opacity) {
      return ( "rgba(" +  parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) +  "," +
        parseInt("0x" + hex.slice(5, 7)) +"," + opacity +  ")"
      );
    },

2.钢笔橡皮还原问题
看生成数据,数据里type:path就是通过路径绘制
所有的橡皮数据都是钢笔数据的属性值,感觉数据删减出必要的属性

 drawObj = new fabric.Path(value["path"], {   //钢笔轨迹
              fill: null,
              stroke: "rgb(0, 0, 0)",    
              strokeWidth: 10,
              strokeLineCap: "round",  //笔头,原型
              erasable: true,  //可擦属性
            });

再追加宽高,top,left就行

**var group = new fabric.Group([
        new fabric.Rect({  //橡皮里都有这个框,推测是橡皮绘制范围
          originX: "center",
          originY: "center",
          left: 0.5,
          top: 0.5,
          width: 196,
          height: 244,
          strokeWidth: 1,
          erasable: true,
        }),
        new fabric.Path(this.eraserBrushPath1, {  //橡皮数据
          left: -27.51,
          top: -83.51,
          width: 37.01,
          height: 262.01,
          stroke: "rgb(0, 0, 0)",
          strokeWidth: 10,
          strokeLineCap: "round",
          globalCompositeOperation: "destination-out",
          path: this.eraserBrushPath1,
        }),
      ]);**

钢笔橡皮绑定,渲染

pencilBrush.clipPath = group;
this.fabricObj.add(pencilBrush);
this.fabricObj.renderAll(); // 重新渲染画布

遇到问题
1.钢笔橡皮还原,循环层级多,不要用fabric.js自带属性fabric.set({}),会出现额外属性,用this.$set的vue自带对象追加属性
2.渲染会显示不全,看数据group是有自带属性的,也不知道为啥删除掉group自带属性就正常了,也不知道为啥

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值