image

Apr 07 2023

cover

Getting Started with Konva.js: Drawing and Transforming Shapes on the Web Canvas

Konva.js is a 2D drawing library for web applications that utilizes the HTML5 Canvas API. It provides an easy-to-use interface for creating and manipulating shapes, images, and text on a canvas. In this blog post, we will explore the features of Konva.js and provide code examples to help you get started.

Installation

To use Konva.js in your web application, you need to include the Konva.js library in your HTML file. You can download Konva.js from the official website or install it using a package manager like npm.

Once you have the Konva.js library included in your project, you can start using its features.


Creating a Stage and Layer

The first step in using Konva.js is to create a stage and a layer. The stage represents the entire canvas, and the layer represents a single drawing surface on the canvas.

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

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

In the above code, we create a new stage with a width and height of 500 pixels and add it to the HTML element with the ID "container". Then we create a new layer and add it to the stage.

Creating Shapes

Konva.js provides several built-in shapes that you can use to create your drawings. Here are some examples:

// Rectangle
const rect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 2
});

// Circle
const circle = new Konva.Circle({
x: 250,
y: 250,
radius: 50,
fill: 'blue',
stroke: 'black',
strokeWidth: 2
});

// Line
const line = new Konva.Line({
points: [100, 100, 200, 200],
stroke: 'green',
strokeWidth: 2
});

// Text
const text = new Konva.Text({
x: 300,
y: 50,
text: 'Hello Konva!',
fontSize: 20,
fontFamily: 'Calibri',
fill: 'black'
});

// Add shapes to layer
layer.add(rect);
layer.add(circle);
layer.add(line);
layer.add(text);

// Draw layer
layer.draw();

In the above code, we create a rectangle, circle, line, and text using the built-in Konva.js shapes. We set the properties of each shape, such as its position, size, color, and stroke width. Then we add each shape to the layer using the add() method and call the draw() method to draw the layer on the canvas.


Transforming Shapes

Konva.js provides several methods to transform shapes, such as scaling, rotating, and moving. Here are some examples:

// Scale rectangle
rect.scale({ x: 2, y: 2 });

// Rotate circle
circle.rotate(45);

// Move line
line.move({ x: 50, y: 50 });

// Animate text
text.to({
x: 100,
y: 100,
duration: 1
});

In the above code, we use the scale() method to scale the rectangle by a factor of 2 in both the x and y directions. We use the rotate() method to rotate the circle by 45 degrees. We use the move() method to move the line by 50 pixels in both the x and y directions.