2

请查看
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();
});

这是我的绘图会话的结果图像。 我在左上角画了一张快乐的脸

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

编辑:来自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 行。我用鼠标在画布的左上角画了一个圆圈。生成的图像如下。 修改后的代码结果

以下是在控制台中打印的。

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

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

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

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

4

2 回答 2

1

我为自己的问题找到了解决方案。但是,如果有人有更好的,那么请发布它。看 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);
  });
});

如果有人解释了为什么我的原始代码不起作用,请发布。结果

于 2021-02-02T02:47:45.547 回答
0

感谢您分享您对我的问题的评论。我面临着类似的问题,只是如果我第一次单击画布上的任何位置。然后抵消问题就消失了。这发生在我以编程方式插入画布的任何对象上。

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

于 2021-02-15T00:37:55.407 回答