KonvaJS:如何用线条将n个形状相互连接起来?

问题描述 投票:0回答:1

我试图在屏幕上绘制n个框并将它们相互连接起来。我能够画出连接它们的盒子和线条,但盒子是可拖动的。我的问题是,当移动一个盒子时,将它连接到其他盒子的线不会随之移动。

我已经在这里试过了另一篇文章,但只能使用2个盒子和1行。

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);

javascript konvajs
1个回答
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);
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.