【发布时间】:2024-08-18 12:15:01
【问题描述】:
我想在 fabric.js 中创建将两个对象连接在一起的箭头。
我在这里有一个 jsFiddle 链接:http://jsfiddle.net/xvcyzh9p/45/(感谢@gco)。
上面允许您创建两个对象(两个矩形)并用一条线将它们连接在一起。
function addChildLine(options) {
canvas.off('object:selected', addChildLine);
// add the line
var fromObject = canvas.addChild.start;
var toObject = options.target;
var from = fromObject.getCenterPoint();
var to = toObject.getCenterPoint();
var line = new fabric.Line([from.x, from.y, to.x, to.y], {
fill: 'red',
stroke: 'red',
strokeWidth: 5,
selectable: false
});
canvas.add(line);
// so that the line is behind the connected shapes
line.sendToBack();
// add a reference to the line to each object
fromObject.addChild = {
// this retains the existing arrays (if there were any)
from: (fromObject.addChild && fromObject.addChild.from) || [],
to: (fromObject.addChild && fromObject.addChild.to)
}
fromObject.addChild.from.push(line);
toObject.addChild = {
from: (toObject.addChild && toObject.addChild.from),
to: (toObject.addChild && toObject.addChild.to) || []
}
toObject.addChild.to.push(line);
// to remove line references when the line gets removed
line.addChildRemove = function () {
fromObject.addChild.from.forEach(function (e, i, arr) {
if (e === line)
arr.splice(i, 1);
});
toObject.addChild.to.forEach(function (e, i, arr) {
if (e === line)
arr.splice(i, 1);
});
}
canvas.addChild = undefined;
}
function addChildMoveLine(event) {
canvas.on(event, function (options) {
var object = options.target;
var objectCenter = object.getCenterPoint();
// udpate lines (if any)
if (object.addChild) {
if (object.addChild.from)
object.addChild.from.forEach(function (line) {
line.set({ 'x1': objectCenter.x, 'y1': objectCenter.y });
})
if (object.addChild.to)
object.addChild.to.forEach(function (line) {
line.set({ 'x2': objectCenter.x, 'y2': objectCenter.y });
})
}
canvas.renderAll();
});
}
我曾尝试查看其他示例以在 fabric.js 中创建箭头,但在 gco 的小提琴中实现一直很痛苦。
我在这方面的最佳尝试可以在这里找到:http://example.legalobjects.com/
我遇到的一些问题是:
- 箭头未按正确方向移动
- 在画布上添加多个箭头时,箭头(或多个箭头)会断裂 - 由于某种原因,它们会“卡住”。
- 箭头/线不在对象周围移动
如果有人有任何想法或可以提供帮助,我将非常感激!
谢谢。
【问题讨论】:
标签: javascript canvas fabricjs