如何 freeDraw fabric.Path 有一定的偏移量?

How to freeDraw fabric.Path with certain offset to it?

我需要能够使用 fabric 的 freeDrawingBrush 绘制一个 fabric.Path 并在鼠标点击 canvas 的位置有一定的偏移量 canvas。

例如: 如果 canvas.getPointer() returns 点 p = {x: 100, y: 100}, 我希望 fabric 在 newP = {x: p.x + 20, y: p.y + 20} (或其他)上画出那个点;

我无法让它工作。我已经试了好几天了,完全没有运气。

@Component({

  private Brush: any;
  private canvas:

  constructor() {
     this.Brush = fabric.util.createClass(fabric.PencilBrush, {
     type: 'myBrush',
     color: 'rgb(134, 10, 230)',
         width: 16,

     initialize: function(canvas) {
         this.callSuper('initialize', canvas);
      },                
    onMouseDown: function(pointer) {
          this.callSuper('onMouseDown', pointer);
  },
    onMouseMove: function(pointer) {
         this.callSuper('onMouseMove', pointer);
      },
  _render: function(ctx) {
     this.callSuper('_render', ctx);
     }
   });
}

ngOnInit() {
    this.canvas = new fabric.Canvas('myCanvas');

    if (this.canvas.freeDrawingBrush) {
      this.canvas.freeDrawingBrush = this.Brush;
    }
    canvas.on("mouse:down", (e) => { 
    let pointer = canvas.getPointer(),
        point = { x: pointer.x + 20, y: pointer.y + 20 };

    Brush.onMouseDown(point);
   }
 }
}

它只适用于第一个绘制的路径。

我自己找到了解决办法。 首先,我像通常使用 canvas.freeDrawingBrush.color = 'transparent';

那样自由绘制路径

然后在 canvas 事件中:

canvas.on('path:created', (o) => { 
        let paths = canvas.getObjects('path').length;
        this.drawPath(o.path);
});

我删除该路径只是为了使用我想要的选项重新绘制它,如下所示:

drawPath(path) {
    canvas.remove(path);

    let offsetY, offsetX, uiValue = this.uiValue;

    //you can use any value you want
    if(this.uiValue < 0){
        offsetY = path.top + 50;
        offsetX = path.left - 50;
    }
    else if(this.uiValue > 0){
        offsetY = path.top + 50;
        offsetX = path.left + 50;
    }

    path.setOptions({
        top: offsetY,
        left: offsetX,
        selectable: false,
        fill: 'transparent', //this did the trick, otherwise it will 
                             //'clipTo' instead of just drawing the path
        stroke: 'blue',
        color: 'blue',      
        globalCompositeOperation: 'destination-out'
    });

    canvas.add(path).renderAll();       
}

就是这样,新路径将准确出现在您想要的位置。