javascript - KonvaJS:如何用线条将 n 个形状相互连接?
问题描述
我正在尝试在屏幕上绘制 n 个框并将它们与线连接起来。我能够绘制连接它们的框和线,但这些框是可拖动的。我的问题是,当一个盒子被移动时,将它连接到其他盒子的线不会随之移动。
我已经在这里尝试过另一篇文章,但这只适用于 2 个盒子和一行。
let box2 = {x:500, y:20, width:150, height:100, color:'green', children:[]}
let box3 = {x:300, y:300, width:150, height:100, color:'blue', children:[]}
let box_1 = {x:20, y:20, width:150, height:100, color:'red', children:[box2, box3]};
let boxes = [box_1, box2, box3];
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: 600,
height: 800
});
var layer = new Konva.Layer();
function drawline(box1, box2){
let startX = box1.getX();
let startY = box1.getY();
let endX = box2.getX()
let endY = box2.getY();
var line = new Konva.Line({
points: [startX, startY, endX, endY],
stroke: 'black',
strokeWidth: 5,
lineCap: 'round',
lineJoin: 'round',
draggable: true
});
layer.add(line);
}
function drawBoxes(listOfBoxes){
for (var i = 0; i < listOfBoxes.length; i++) {
let rect = listOfBoxes[i];
var box1 = new Konva.Rect({
x: rect['x'],
y: rect['y'],
width: rect['width'],
height: rect['height'],
fill: rect['color'],
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(box1);
for (var child = 0; child < rect['children'].length; child++) {
var box2 = new Konva.Rect({
x: rect['children'][child]['x'],
y: rect['children'][child]['y'],
width: rect['children'][child]['width'],
height: rect['children'][child]['height'],
fill: rect['children'][child]['color'],
stroke: 'black',
strokeWidth: 4,
draggable: true
});
drawline(box1, box2);
}
}
}
drawBoxes(boxes);
stage.add(layer);
解决方案
当盒子移动时,您必须手动更新线的位置。您可以dragmove
在这种情况下使用事件。
function updateLinePosition(line, box1, box2) {
let startX = box1.getX();
let startY = box1.getY();
let endX = box2.getX()
let endY = box2.getY();
line.points([startX, startY, endX, endY]);
}
function drawline(box1, box2){
var line = new Konva.Line({
stroke: 'black',
strokeWidth: 5,
lineCap: 'round',
lineJoin: 'round',
draggable: true
});
updateLinePosition(line, box1, box2);
layer.add(line);
box1.on('dragmove', () => {
updateLinePosition(line, box1, box2);
})
box2.on('dragmove', () => {
updateLinePosition(line, box1, box2);
})
}
推荐阅读
- c# - C#如何等待异步任务,直到它指示继续
- javascript - 一次两个菜单都处于活动状态
- c# - 运行时默认值不相等
- mysql - 创建外键时出错:MySQL 错误 1215:无法添加外键约束
- ios - Xcode 10 Beta 6 Playground 中未调用 Deinit 方法
- regex - 正则表达式:PCRE 原子组不起作用
- sql - 如何使用 LISTAGG 和 Regexp_replace 获得不同的值
- c# - 删除某些控件后如何删除(删除)文本框之间的空格?
- c++ - 在c ++中使用向量在带有循环的动态数组中插入值
- javascript - 变量未定义(TypeError:无法读取属性'todos' of null)ReactJS