Konva can’t connect two objects with a line and update its position automatically. You have to update a line manually as you need it. Usually we need to update line position when a user drag one of the connected objects. In simple cases in can be that:
const obj1 = new Konva.Circle({ ...obj1Props }) const obj2= new Konva.Circle({ ...obj2Props });
<body> <divid="container"></div> <script> var width = window.innerWidth; var height = window.innerHeight;
var stage = new Konva.Stage({ container: 'container', width: width, height: height });
var layer = new Konva.Layer(); stage.add(layer);
// function to generate a list of "targets" (circles) functiongenerateTargets(){ var number = 10; var result = []; while (result.length < number) { result.push({ id: 'target-' + result.length, x: stage.width() * Math.random(), y: stage.height() * Math.random() }); } return result; }
var targets = generateTargets();
// function to generate arrows between targets functiongenerateConnectors(){ var number = 10; var result = []; while (result.length < number) { varfrom = 'target-' + Math.floor(Math.random() * targets.length); var to = 'target-' + Math.floor(Math.random() * targets.length); if (from === to) { continue; } result.push({ id: 'connector-' + result.length, from: from, to: to }); } return result; }
functiongetConnectorPoints(from, to){ const dx = to.x - from.x; const dy = to.y - from.y; let angle = Math.atan2(-dy, dx);
// update all objects on the canvas from the state of the app functionupdateObjects(){ targets.forEach(target => { var node = layer.findOne('#' + target.id); node.x(target.x); node.y(target.y); }); connectors.forEach(connect => { var line = layer.findOne('#' + connect.id); var fromNode = layer.findOne('#' + connect.from); var toNode = layer.findOne('#' + connect.to);
// generate nodes for the app connectors.forEach(connect => { var line = new Konva.Arrow({ stroke: 'black', id: connect.id, fill: 'black' }); layer.add(line); });