我正在尝试在屏幕上绘制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);
答案 0 :(得分:0)
移动框时,必须手动更新行的位置。在这种情况下,您可以使用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);
})
}