Skip to main content

HTML5 Canvas Drag and Drop a Line

To drag and drop a line with Konva, we can set the draggable property of the config object to true when the line is instantiated, or we can use the draggable() method.

Note: (!) dragging a line will NOT change the points property. Instead x and y properties of the line are changed.

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();

const redLine = new Konva.Line({
  x: 50,
  y: 50,
  points: [0, 0, 150, 0],
  stroke: 'red',
  strokeWidth: 15,
  lineCap: 'round',
  lineJoin: 'round',
  draggable: true,
});

// add cursor styling
redLine.on('mouseover', function () {
  document.body.style.cursor = 'pointer';
});
redLine.on('mouseout', function () {
  document.body.style.cursor = 'default';
});

layer.add(redLine);
stage.add(layer);