### Install Konva (npm)
Source: https://konvajs.org/docs/index.html
Install Konva using npm.
```bash
npm install konva
```
--------------------------------
### Quick Example
Source: https://konvajs.org/docs/index.html
A quick example demonstrating how to create a stage, a layer, a draggable rectangle, and add an event listener to change its color on click.
```javascript
// Create a stage (container for all layers)
const stage = new Konva.Stage({
container: 'container',
width: 500,
height: 400,
});
// Create a layer
const layer = new Konva.Layer();
stage.add(layer);
// Create a draggable rectangle
const rect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 80,
fill: 'cornflowerblue',
shadowBlur: 5,
cornerRadius: 4,
draggable: true,
});
layer.add(rect);
// Add event listener
rect.on('click tap', () => {
rect.fill(Konva.Util.getRandomColor());
});
```
--------------------------------
### Basic Drag and Drop Setup with Transformer
Source: https://konvajs.org/docs/drag_and_drop/Drop_Events.html
This example demonstrates attaching a Transformer to a Rect and handling drop events. It shows how to manage layers correctly for the Transformer to follow the dragged element.
```javascript
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
var layer = new Konva.Layer();
stage.add(layer);
var rect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: 'red',
draggable: true
});
layer.add(rect);
var tr = new Konva.Transformer({
nodes: [rect]
});
layer.add(tr);
layer.draw();
```
--------------------------------
### Install Konva (script tag)
Source: https://konvajs.org/docs/index.html
Include Konva using a script tag from a CDN.
```html
```
--------------------------------
### Complete Konva Example (v10+)
Source: https://konvajs.org/docs/nodejs/nodejs-setup
A full example demonstrating Konva setup and canvas export in Node.js using either Canvas or Skia backend.
```javascript
import Konva from 'konva';
import 'konva/canvas-backend'; // or 'konva/skia-backend'
// Create a stage
const stage = new Konva.Stage({
container: 'container', // This will be ignored in Node.js
width: 800,
height: 600
});
// ... the rest of your konva code
// Export as data URL
const dataURL = stage.toDataURL();
```
--------------------------------
### Vanilla JS: Setup and Drag Start Listener
Source: https://konvajs.org/docs/sandbox/Drop_DOM_Element.html
This snippet sets up the HTML structure for draggable images and attaches a dragstart event listener to capture the source URL of the image being dragged.
```javascript
import Konva from 'konva';
const width = window.innerWidth;
const height = window.innerHeight;
// Add DOM elements to render outside the container
document.getElementById('container').insertAdjacentHTML(
'beforebegin',
`
Drag&drop yoda into the grey area.
`
);
// Style the container with grey background
document.getElementById('container').style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
// Create stage and layer
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height - 150, // leave space for the DOM elements
});
const layer = new Konva.Layer();
stage.add(layer);
// Track URL of the dragging element
let itemURL = '';
document
.getElementById('drag-items')
.addEventListener('dragstart', function (e) {
itemURL = e.target.src;
```
--------------------------------
### Install React Konva
Source: https://konvajs.org/docs/react/index.html
Install react-konva and konva using npm. This is the initial step to begin using the library.
```bash
npm install react-konva konva --save
```
--------------------------------
### React Konva App Setup
Source: https://konvajs.org/docs/sandbox/Image_Labeling.html
Basic setup for a React application using Konva and react-konva. This file is the entry point for the React application.
```javascript
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import App from "./components/App";
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
```
--------------------------------
### Install Konva with Skia Backend (v10+)
Source: https://konvajs.org/docs/nodejs/nodejs-setup
Install Konva and the Skia backend for improved performance in Node.js.
```bash
npm install konva skia-canvas
```
--------------------------------
### Install svelte-konva and konva
Source: https://konvajs.org/docs/svelte/index.html
Install the necessary packages via npm to begin using svelte-konva.
```bash
npm i svelte-konva konva
```
--------------------------------
### Install vue-konva and konva
Source: https://konvajs.org/docs/vue/index.html
Install the necessary packages using npm. This command installs both vue-konva and konva.
```bash
npm install vue-konva konva --save
```
--------------------------------
### Install Konva with Canvas Backend (v10+)
Source: https://konvajs.org/docs/nodejs/nodejs-setup
Install Konva and the default Canvas backend for Node.js environments.
```bash
npm install konva canvas
```
--------------------------------
### Undo/Redo and Save/Load Demo Setup (Vanilla JS)
Source: https://konvajs.org/docs/data_and_serialization/Best_Practices.html
Initial setup for a Konva.js application demonstrating undo/redo and save/load functionality using vanilla JavaScript. It includes state management, history tracking, stage and layer creation, and UI button setup.
```javascript
import Konva from 'konva';
// Initial state
let state = {
images: [
{ x: 50, y: 50, filter: 'none' },
{ x: 150, y: 50, filter: 'blur' }
]
};
// History for undo/redo
const history = [JSON.stringify(state)];
let historyStep = 0;
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
const layer = new Konva.Layer();
stage.add(layer);
// Create container
const container = document.createElement('div');
container.style.position = 'relative';
document.body.appendChild(container);
// Create button container
const buttonContainer = document.createElement('div');
buttonContainer.style.position = 'absolute';
buttonContainer.style.top = '10px';
buttonContainer.style.left = '10px';
buttonContainer.style.zIndex = '10';
container.appendChild(buttonContainer);
// Create UI buttons
const addButton = document.createElement('button');
addButton.textContent = 'Add Image';
addButton.style.margin = '0 5px';
buttonContainer.appendChild(addButton);
const undoButton = document.createElement('button');
undoButton.textContent = 'Undo';
undoButton.style.margin = '0 5px';
buttonContainer.appendChild(undoButton);
const redoButton = document.createElement('button');
redoButton.textContent = 'Redo';
redoButton.style.margin = '0 5px';
buttonContainer.appendChild(redoButton);
// Move stage container into our container
const stageContainer = document.getElementById('container');
container.appendChild(stageContainer);
stageContainer.style.position = 'absolute';
```
--------------------------------
### Install react-konva and konva
Source: https://konvajs.org/docs/faq.html
Install the necessary packages for using Konva.js with React.
```bash
npm install react-konva konva
```
--------------------------------
### Setup Konva Stage and Layer (Vanilla JS)
Source: https://konvajs.org/docs/sandbox/Animation_Stress_Test.html
Initializes a Konva stage and a layer with listening disabled for performance optimization. This setup is for the vanilla JavaScript version of the demo.
```javascript
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
/*
* setting the listening property to false will improve
* drawing performance because the rectangles won't have to be
* drawn onto the hit graph
*/
const layer = new Konva.Layer({
listening: false,
});
```
--------------------------------
### Snap Single Rect to Guide Line
Source: https://konvajs.org/docs/drag_and_drop/Simple_Drag_Bounds.html
Use the `dragmove` event to snap a single rectangle to a guide line when it approaches. This example shows the basic logic for updating the rectangle's position.
```javascript
rect.on('dragmove' , e => {
e.target.x(guideLine.x)
....
})
```
--------------------------------
### Vanilla JavaScript Setup
Source: https://konvajs.org/docs/select_and_transform/Force_Update.html
Sets up a Konva stage, layer, and a group containing text and a rectangle. This forms the base for demonstrating the force update functionality.
```javascript
import Konva from 'konva';
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
const layer = new Konva.Layer();
stage.add(layer);
const group = new Konva.Group({
x: 50,
y: 50,
draggable: true,
});
layer.add(group);
const text = new Konva.Text({
text: 'Some text here',
fontSize: 24,
});
group.add(text);
const rect = new Konva.Rect({
width: text.width(),
height: text.height(),
fill: 'yellow',
});
group.add(rect);
// add the shape to the layer
rect.moveToBottom();
```
--------------------------------
### Konva Tween with EaseOut Easing
Source: https://konvajs.org/docs/tweens/Common_Easings.html
Example of creating a Konva.Tween with the EaseOut easing function. This is useful for animations that start fast and slow down towards the end.
```javascript
var redBox = new Konva.Line({ ... });
redBox.tween = new Konva.Tween({
node: redBox,
scaleX: 2,
scaleY: 1.5,
easing: Konva.Easings.EaseOut,
duration: 1
});
```
--------------------------------
### Vue-Konva CDN Setup
Source: https://konvajs.org/docs/vue/index.html
Integrate Vue-Konva into an HTML file using CDNs. This method includes Vue.js, Konva, and vue-konva, and sets up a basic circle example.
```html
```
--------------------------------
### Transformer with Star Shape and Stroke
Source: https://konvajs.org/docs/select_and_transform/Ignore_Stroke_On_Transform.html
This example demonstrates how a Konva.Transformer might not enclose the stroke of a shape like a Star. It shows the initial setup of the Star and the Transformer.
```javascript
var star = new Konva.Star({
x: 250,
y: 60,
numPoints: 5,
innerRadius: 40,
outerRadius: 70,
draggable: true,
fill: "red",
stroke: "black",
strokeWidth: 50,
});
layer.add(star);
var tr = new Konva.Transformer({
nodes: [star],
});
layer.add(tr);
```
--------------------------------
### React Konva Text and Rect Example
Source: https://konvajs.org/docs/shapes/Text.html
Demonstrates creating simple and complex text along with a rectangle in a React Konva application. Includes setup for stage, layer, text, and rectangle components.
```jsx
import { Stage, Layer, Text, Rect } from 'react-konva';
const text = `COMPLEX TEXT\n\nAll the world's a stage, and all the men and women merely players. They have their exits and their entrances.`;
const App = () => {
return (
);
};
export default App;
```
--------------------------------
### Basic KonvaJS Setup with Draggable Shapes
Source: https://konvajs.org/docs/posts/Position_vs_Offset.html
Demonstrates the initial setup of a Konva stage, layer, and adds a draggable rectangle and circle. This code illustrates the default behavior of x and y properties for different shape types.
```javascript
import Konva from 'konva';
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
var layer = new Konva.Layer();
var rect = new Konva.Rect({
x: 20,
y: 20,
width: 100,
height: 100,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});
// add the shape to the layer
layer.add(rect);
var circle = new Konva.Circle({
x: 150,
y: 120,
radius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});
// add the shape to the layer
layer.add(circle);
```
--------------------------------
### Basic React Konva Canvas Example
Source: https://konvajs.org/docs/react/index.html
A simple React component demonstrating how to create a canvas with draggable shapes like Text, Rect, and Circle using react-konva. Ensure you have react-konva and konva installed.
```jsx
import React from 'react';
import { Stage, Layer, Rect, Circle, Text } from 'react-konva';
const App = () => {
return (
);
};
export default App;
```
--------------------------------
### Initialize Konva Stage and Layers with Performance Settings
Source: https://konvajs.org/docs/performance/All_Performance_Tips.html
Set up the Konva stage and layers with performance optimizations. Use `listening: false` for background layers that do not require interaction. This example demonstrates creating a stage, background layer, main layer, and a drag layer.
```javascript
import Konva from 'konva';
// Create stage with good performance settings
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
// Create layers with performance optimizations
const backgroundLayer = new Konva.Layer({ listening: false });
const mainLayer = new Konva.Layer();
const dragLayer = new Konva.Layer();
stage.add(backgroundLayer);
stage.add(mainLayer);
stage.add(dragLayer);
```
--------------------------------
### Accessing Konva Node using Refs API
Source: https://konvajs.org/docs/react/Access_Konva_Nodes.html
Use the `useRef` hook to get a reference to a Konva node. This reference can then be used to directly interact with the Konva API, for example, logging the Konva instance.
```javascript
import React from 'react';
import { Stage, Layer, Circle } from 'react-konva';
const App = () => {
const shapeRef = React.useRef(null);
React.useEffect(() => {
// it will log `Konva.Circle` instance
console.log(shapeRef.current);
});
return (
);
};
export default App;
```
--------------------------------
### Main App Vue Component Setup
Source: https://konvajs.org/docs/sandbox/Animals_on_the_Beach_Game.html
Sets up the main application component, including stage configuration, score tracking, animal data, and event handlers.
```javascript
const stageSize = {
width: 578,
height: 530
};
const score = ref(0);
const animals = {
snake: { x: 10, y: 70, outline: { x: 275, y: 350 } },
giraffe: { x: 90, y: 70, outline: { x: 390, y: 250 } },
monkey: { x: 275, y: 70, outline: { x: 300, y: 420 } },
lion: { x: 400, y: 70, outline: { x: 100, y: 390 } }
};
const handleScore = () => score.value++;
```
--------------------------------
### Vue.js: Canvas Setup with Shapes and Transformer
Source: https://konvajs.org/docs/select_and_transform/Basic_demo.html
This snippet demonstrates a Vue.js implementation for a Konva.js canvas. It uses v-for to render rectangles and includes a v-transformer for interactive manipulation, mirroring the React example's functionality.
```vue
handleDragEnd(e, i)"
@transformend="(e) => handleTransformEnd(e, i)"
ref="rectRefs"
/>
```
--------------------------------
### Vanilla JS: Basic Layering Setup
Source: https://konvajs.org/docs/groups_and_layers/Layering.html
Sets up a Konva stage, a layer, and two draggable rectangles (yellow and red). This forms the basis for demonstrating layering techniques.
```javascript
import Konva from 'konva';
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
const layer = new Konva.Layer();
const yellowBox = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});
const redBox = new Konva.Rect({
x: 100,
y: 100,
width: 100,
height: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});
layer.add(yellowBox);
layer.add(redBox);
stage.add(layer);
```
--------------------------------
### Vanilla JavaScript Konva.js Setup
Source: https://konvajs.org/docs/sandbox/Animals_on_the_Beach_Game.html
Initializes a Konva stage and layers for a game. Loads a background image and prepares layers for animal shapes.
```javascript
import Konva from 'konva';
// create stage
const stage = new Konva.Stage({
container: 'container',
width: 578,
height: 530,
});
const background = new Konva.Layer();
const animalLayer = new Konva.Layer();
const animalShapes = [];
let score = 0;
// create and load background image
const backgroundImage = new Image();
backgroundImage.onload = function() {
const backgroundKonvaImage = new Konva.Image({
image: backgroundImage,
x: 0,
y: 0,
width: stage.width(),
height: stage.height(),
});
background.add(backgroundKonvaImage);
backgroundKonvaImage.moveToBottom();
};ackgroundImage.src = 'https://konvajs.org/assets/beach.png';
```
--------------------------------
### Get Ctrl KeyCode on Mouse Click Event
Source: https://konvajs.org/docs/events/Keyboard_Events.html
This example shows how to correctly retrieve the Ctrl key code during a mouse click event. It emphasizes the need to access the native event object for key code information.
```javascript
stage.on('click', (e) => {
var mousePos = stage.getPointerPosition();
if (e.keyCode === 17) {
newRectangle(mousePos.x, mousePos.y);
}
});
```
```javascript
// You need to access native event object. "e.evt.keyCode"
```
--------------------------------
### Vanilla JavaScript Canvas Overlay Setup
Source: https://konvajs.org/docs/sandbox/Canvas_Overlay.html
Initializes a Konva stage and layer for drawing. Sets up control elements like buttons and an opacity slider.
```javascript
import Konva from 'konva';
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
var layer = new Konva.Layer();
stage.add(layer);
var container = document.getElementById('container');
var controls = document.createElement('div');
controls.style.cssText = 'margin-bottom: 8px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; font: 13px Arial, sans-serif;';
function makeBtn(label) {
var btn = document.createElement('button');
btn.textContent = label;
btn.dataset.active = 'false';
btn.style.cssText = 'padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; background: #f5f5f5; cursor: pointer; font-size: 13px;';
return btn;
}
var colorBtn = makeBtn('Color');
var textBtn = makeBtn('Text');
var gradientBtn = makeBtn('Gradient');
var opLabel = document.createElement('label');
opLabel.style.cssText = 'display: flex; align-items: center; gap: 6px; font-size: 13px;';
opLabel.appendChild(document.createTextNode('Opacity:'));
var opSlider = document.createElement('input');
opSlider.type = 'range';
```
--------------------------------
### Vanilla JS: Setup and Animation Control
Source: https://konvajs.org/docs/animations/Stop_Animation.html
Sets up a Konva stage, layer, and circle, then adds buttons to control the animation. Use this for basic Konva animation control.
```javascript
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 circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);
// add buttons
const container = document.createElement('div');
document.body.appendChild(container);
container.style.position = 'absolute';
container.style.top = '0px';
container.style.left = '0px';
const startBtn = document.createElement('button');
startBtn.textContent = 'Start Animation';
container.appendChild(startBtn);
const stopBtn = document.createElement('button');
stopBtn.textContent = 'Stop Animation';
container.appendChild(stopBtn);
```
--------------------------------
### Install Konva for Node.js
Source: https://konvajs.org/docs/faq.html
Install Konva and the canvas package for server-side rendering.
```bash
npm install konva canvas
```
--------------------------------
### Initialize Konva Stage and Layer
Source: https://konvajs.org/docs/sandbox/Canvas_Sticker.html
Sets up the Konva stage and a layer to draw on. This is the foundational step for any Konva application.
```javascript
import Konva from 'konva';
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
var layer = new Konva.Layer();
stage.add(layer);
```
--------------------------------
### Initializing Gesture Event Demo
Source: https://konvajs.org/docs/sandbox/Gestures.html
Asynchronously loads Hammer.js and touch-emulator, enables touch emulation for desktop, and sets up Konva event capturing.
```javascript
async function initDemo() {
try {
await loadScript('https://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js');
await loadScript('https://konvajs.org/js/hammer-konva.js');
// emulate touches on desktop
TouchEmulator();
Konva.hitOnDragEnabled = true;
Konva.captureTouchEventsEnabled = true;
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
const layer = new Konva.Layer();
stage.add(layer);
} catch (error) {
console.error('Failed to initialize demo:', error);
}
}
```
--------------------------------
### Install ng2-konva and konva
Source: https://konvajs.org/docs/faq.html
Install the necessary packages for using Konva.js with Angular.
```bash
npm install ng2-konva konva
```
--------------------------------
### Initialize Konva Stage and Layer
Source: https://konvajs.org/docs/sandbox/Jumping_Bunnies.html
Sets up the Konva stage and a FastLayer for efficient rendering. This is a foundational step for any Konva application.
```javascript
import Konva from 'konva';
// Set up stage and layer
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
const layer = new Konva.FastLayer();
stage.add(layer);
```
--------------------------------
### Install svelte-konva and konva
Source: https://konvajs.org/docs/faq.html
Install the necessary packages for using Konva.js with Svelte.
```bash
npm install svelte-konva konva
```
--------------------------------
### Install vue-konva and konva
Source: https://konvajs.org/docs/faq.html
Install the necessary packages for using Konva.js with Vue.
```bash
npm install vue-konva konva
```
--------------------------------
### Vanilla JS Konva Animation Setup
Source: https://konvajs.org/docs/performance/Optimize_Animation.html
Basic setup for Konva stage, layer, and shapes in vanilla JavaScript. Demonstrates creating a complex star shape and a simple circle, with the star shape being cached for performance.
```javascript
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);
// Create a complex star shape
const star = new Konva.Star({
x: stage.width() / 2,
y: stage.height() / 2,
numPoints: 6,
innerRadius: 40,
outerRadius: 70,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
});
// Cache the shape for better performance
star.cache();
layer.add(star);
// Create simple circle that doesn't need caching
const circle = new Konva.Circle({
x: 100,
y: 100,
radius: 20,
fill: 'red',
});
layer.add(circle);
```
--------------------------------
### Basic Konva Text Setup
Source: https://konvajs.org/docs/sandbox/Editable_Text.html
Initializes a Konva stage, layer, and a draggable text node. This serves as the foundation for adding interactive elements.
```javascript
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 textNode = new Konva.Text({
text: 'Some text here',
x: 50,
y: 80,
fontSize: 20,
draggable: true,
width: 200,
});
layer.add(textNode);
const tr = new Konva.Transformer({
node: textNode,
enabledAnchors: ['middle-left', 'middle-right'],
boundBoxFunc: function (oldBox, newBox) {
newBox.width = Math.max(30, newBox.width);
return newBox;
},
});
```