Skip to main content

HTML5 canvas Line Tutorial

To create line shapes with Konva, we can instantiate a Konva.Line() object. Lines can be configured in different ways to create various shapes like simple lines, splines, blobs, and polygons.

For full list of properties and methods, see the Line API Reference.

Simple Line

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

const redLine = new Konva.Line({
  points: [5, 70, 140, 23, 250, 60, 300, 20],
  stroke: 'red',
  strokeWidth: 15,
  lineCap: 'round',
  lineJoin: 'round'
});

// dashed line
const greenLine = new Konva.Line({
  points: [5, 70, 140, 23, 250, 60, 300, 20],
  stroke: 'green',
  strokeWidth: 2,
  lineJoin: 'round',
  dash: [33, 10]
});

greenLine.y(50);
layer.add(redLine, greenLine);

Spline (Curved Line)

To create a curved line, add the tension property:

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

const line = new Konva.Line({
  points: [5, 70, 140, 23, 250, 60, 300, 20],
  stroke: 'red',
  strokeWidth: 15,
  lineCap: 'round',
  lineJoin: 'round',
  tension: 1
});

layer.add(line);

Polygon

To create a polygon, set the closed property to true:

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

const polygon = new Konva.Line({
  points: [73, 192, 73, 160, 340, 23, 500, 109, 499, 139, 342, 93],
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 5,
  closed: true
});

layer.add(polygon);

Blob

To create a blob, combine closed and tension properties:

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

const blob = new Konva.Line({
  points: [23, 20, 23, 160, 70, 93, 150, 109, 290, 139, 270, 93],
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 5,
  closed: true,
  tension: 0.3
});

layer.add(blob);