Konva

Konva is an HTML5 Canvas JavaScript framework. It enables high performance drawing capabilities for desktop and mobile applications.

How does it works


  • Every thing starts from Konva.Stage
  • Konva.Stage contains several layers ( Konva.Layer )
  • Each layer contains shapes ( Konva.Shape ) or groups ( Konva.Group )
  • Each group contains shapes ( Konva.Shape ) or other groups ( Konva.Group )

  • Add the Konva JS code before you use it like the following
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
1

Example


Here we want to use Konva to draw a circle.

HTML part: Add the Konva JS code and prepare an element for Konva (set an id for that element).

<h2>Konva's Circle</h2>
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
<div id="container"></div>
1
2
3

JS part: Add the following code

// first we need to create a stage
var stage = new Konva.Stage({
  container: 'container',   // id of container <div>
  width: 160,
  height: 160
});

// then create a layer
var layer = new Konva.Layer();

// create our shape
var circle = new Konva.Circle({
  x: stage.width() / 2,   // x position of the center
  y: stage.height() / 2,  // y position of the center
  radius: 70,             // circle radius
  fill: 'red',            // color to fill the area
  stroke: 'black',        // color to draw the line
  strokeWidth: 4          // line width
});

// add the shape to the layer
layer.add(circle);

// add the layer to the stage
stage.add(layer);

// draw the image
layer.draw();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Result



Exercise

Try to change the properties of the circle, for example, fill color, border color, size, etc.