Introduction to Konva
Konva is a 2D canvas library for the web that extends HTML 5 Canvas API. It is an easy to use JavaScript library for creating complex 2D graphical applications like gaming, data visualization, and art tools. Konva boasts high performance and a rich API that’s both flexible and efficient.
Setting Up Konva
// Include Konva library
<script src="https://cdn.jsdelivr.net/npm/konva@8.3.5/konva.min.js"></script>
// Create a Konva Stage
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
// Add a Konva Layer
const layer = new Konva.Layer();
stage.add(layer);
API Examples
Creating Shapes
// Create a circle
const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
// Add the circle to the layer
layer.add(circle);
// Drawing a rectangle
const rectangle = new Konva.Rect({
x: 20,
y: 20,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 2,
});
layer.add(rectangle);
Transforming Shapes
// Rotate the circle
circle.rotate(30);
// Scale the rectangle
rectangle.scale({ x: 1.5, y: 1.5 });
// Translate the circle
circle.x(circle.x() + 50);
Animating Shapes
// Create an animation function
const anim = new Konva.Animation(function(frame) {
circle.x(200 + 100 * Math.sin(frame.time * 2 * Math.PI / 2000));
}, layer);
anim.start();
Handling Events
// Change color on click
circle.on('click', function() {
this.fill('blue');
layer.draw();
});
// Display mouse position
stage.on('mousemove', function() {
const mousePos = stage.getPointerPosition();
console.log('Mouse position: x=' + mousePos.x + ', y=' + mousePos.y);
});
App Example: Simple Interactive Drawing
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/konva@8.3.5/konva.min.js"></script>
</head>
<body>
<div id="container"></div>
<script>
// Initialize Stage and Layer
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
const layer = new Konva.Layer();
stage.add(layer);
// Drawing logic
stage.on('mousedown', function() {
const mousePos = stage.getPointerPosition();
const circle = new Konva.Circle({
x: mousePos.x,
y: mousePos.y,
radius: 20,
fill: 'red',
});
layer.add(circle);
layer.draw();
});
</script>
</body>
</html>
In conclusion, Konva is a powerful and flexible library that allows for the creation of complex and high-performance 2D graphics applications. Whether you are working on a simple project or a large-scale application, Konva provides the necessary tools to bring your ideas to life effectively.
Hash: 0806683e3665b61c4180b8e848c68121f0c37c3db9cf1f2e5e90993373be2be8