Introduction to Konva
Konva is an incredibly powerful 2D canvas library for JavaScript that enables developers to create complex and performant HTML5 canvas applications. It is particularly popular for applications that require smooth and interactive graphics, such as games or data visualization tools. With Konva, developers can leverage a wide array of APIs to add, manipulate, and animate shapes and layers seamlessly. Below are some detailed API examples along with code snippets to help you get started with Konva.
Useful Konva API Examples
Creating a Stage
The first step in using Konva is to create a stage which acts as a container for everything else.
const stage = new Konva.Stage({ container: 'container', // id of containerwidth: window.innerWidth, height: window.innerHeight, });Adding a Layer
Layers are used to group shapes and optimize redrawing.
const layer = new Konva.Layer(); stage.add(layer);Drawing Shapes
Konva supports various shapes. A common one is a rectangle:
const rect = new Konva.Rect({ x: 20, y: 20, width: 100, height: 50, fill: 'red', stroke: 'black', strokeWidth: 2, }); layer.add(rect); layer.draw();Handling Events
Event handling is easy with Konva. You can bind events directly to shapes:
rect.on('click', function () { alert('Rectangle clicked.'); });Animating Shapes
Animation is straightforward with Konva’s built-in animation support:
const anim = new Konva.Animation(function(frame) { rect.rotate(1); }, layer); anim.start();Image Handling
You can also work with images in Konva:
const imageObj = new Image(); imageObj.onload = function() { const image = new Konva.Image({ x: 50, y: 50, image: imageObj, width: 100, height: 100, }); layer.add(image); layer.draw(); }; imageObj.src = 'path/to/image.jpg';Application Example: Interactive Canvas App
Using the APIs discussed above, let’s create a simple interactive application where you can add shapes by clicking on the canvas.
Konva Interactive App With this simple app, you can click anywhere on the canvas to add new rectangles with random fill colors.
Hash: 0806683e3665b61c4180b8e848c68121f0c37c3db9cf1f2e5e90993373be2be8