如何在自由绘图中重复路径?

How to repeat Paths in Free Drawing?

请看
https://stackblitz.com/edit/js-wxidql
这是我的代码。

import { fabric } from "fabric";

const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
  let mousePath = e.path;
  let offsetPath = new fabric.Path();
  let offsetLeft = mousePath.left + 60;
  let offsetTop = mousePath.top + 60;
  offsetPath.setOptions({
    path: mousePath.path,
    left: offsetLeft,
    top: offsetTop,
    width: mousePath.width,
    height: mousePath.height,
    fill: '',      
    stroke: 'black'       
  });
  canvas.add(offsetPath);
  canvas.requestRenderAll();
});

这是我的绘图会话的结果图像。

我用鼠标在canvas左上角画了笑脸。 偏移图像是由我的代码添加的。 如何更改我的代码以使偏移绘图看起来像用鼠标绘制的那样?

编辑:来自https://github.com/fabricjs/fabric.js/wiki/When-to-call-setCoords 我尝试使用
offsetDraw.setCoords(); 但是我找不到让它工作的方法。

编辑:我在这里展示的是一个最小化的例子。我正在做一个更大的项目,我在其中保存用户绘制的每条路径。后来我在像序列这样的动画中重新创建了这些路径。

编辑:为了理解 fabricjs,我对代码做了一些更改。

const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
  let mousePath = e.path;
  let offsetPath = new fabric.Path();
  let offsetLeft = mousePath.left + 60;
  let offsetTop = mousePath.top + 60;
  offsetPath.setOptions({
    path: mousePath.path,
    //left: offsetLeft,
    //top: offsetTop,
    width: mousePath.width,
    height: mousePath.height,
    fill: '',      
    stroke: 'black'       
  });
  canvas.add(offsetPath);
  canvas.requestRenderAll();
  console.log("mousePath left " + mousePath.left + " top " + mousePath.top);
  console.log("offsetPath left " + offsetPath.left + " top " + offsetPath.top);
});

在该代码中,我注释掉了 offsetPath 的 left 和 top 属性的设置并添加了 console.log 行。我用鼠标在 canvas 的左上角画了一个圆圈。结果图像如下。

控制台打印了以下内容。

mousePath left 7.488148148148148 top 10.5
offsetPath left -0.5 top -0.5

我不明白结果。为什么在那个位置渲染偏移圆?

编辑:我用鼠标画了另一个测试。

看来代码很好地重复了同心圆的路径。但是,垂直线被移出了它们的正确位置。它们的位移随着距中心距离的增加而增加。为什么?

我找到了解决我自己问题的方法。但是,如果有人有更好的,那么请 post 它。看着 https://stackblitz.com/edit/js-ncxvpg
以下是代码。

const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
  let mousePath = e.path;
  mousePath.clone(clone => {
    clone.setOptions({
      left: mousePath.left + 100,
      top: mousePath.top + 100
    });
    canvas.add(clone);
  });
});

如果有人能解释为什么我的原始代码不起作用,请 post 解释一下。

感谢分享您对我的问题的评论。我面临着类似的问题,只是如果我第一次点击 Canvas 上的任何地方。然后偏移问题就消失了。对于我以编程方式插入到 canvas.

中的任何对象,都会发生这种情况

就我而言,我怀疑 canvas.pointer 与当前鼠标位置有一些偏移。但是,当我单击并添加一个非常小的 1 像素路径时,指针偏移就会得到纠正。在此之后,以编程方式创建的所有后续路径或对象都会显示在正确的位置。