请查看
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
我不明白结果。为什么偏移圆在那个位置渲染?
代码似乎很好地重复了同心圆的路径。但是,垂直线被移出正确的位置。它们的位移随着距中心距离的增加而增加。为什么?


