If you prefer using Konva.js for handling the canvas and drawing functionalities, you can integrate it into a Vue 3 application. Konva is a robust 2D canvas library that offers rich functionalities for drawing and manipulating shapes.
Here's a step-by-step guide on how to create an image annotation tool using Konva.js in Vue 3.
Step-by-Step Guide
1. Set up your Vue 3 Project
First, ensure you have Vue CLI installed, and create a new Vue 3 project:
npm install -g @vue/cli
vue create image-annotation-tool
Navigate to the newly created project directory:
cd image-annotation-tool
2. Install Konva and Vue Konva
Add Konva.js and Vue Konva libraries to your project:
npm install konva @konva/vue3
3. Create the Vue Component
Create a new component named ImageAnnotationKonva.vue inside the src/components directory:
<template>
<div>
<input type="file" @change="handleImageUpload" accept="image/*" />
<div id="canvas-container">
<v-stage ref="stage" :config="{ width: containerWidth, height: containerHeight }">
<v-layer ref="layer">
<v-image :config="imageConfig" v-if="imageConfig"></v-image>
<v-rect
v-for="rect in rectangles"
:key="rect.id"
:config="rect"
@mousedown="startDrawing"
@mouseup="finishDrawing"
@mousemove="updateDrawing"
></v-rect>
<v-rect
v-if="newRect"
:config="newRect"
@mousedown="startDrawing"
@mouseup="finishDrawing"
@mousemove="updateDrawing"
></v-rect>
</v-layer>
</v-stage>
</div>
</div>
</template>
<script>
import { ref, reactive, onMounted } from 'vue';
import { Stage, Layer, Rect, Image } from '@konva/vue3';
import Konva from 'konva';
export default {
name: 'ImageAnnotationKonva',
components: {
'v-stage': Stage,
'v-layer': Layer,
'v-rect': Rect,
'v-image': Image,
},
setup() {
const containerWidth = 600;
const containerHeight = 400;
const stage = ref(null);
const layer = ref(null);
const imageConfig = ref(null);
const rectangles = reactive([]);
let newRect = ref(null);
const handleImageUpload = (event) => {
const reader = new FileReader();
reader.onload = function (e) {
const imageObj = new Image();
imageObj.onload = function () {
const konvaImage = new Konva.Image({
image: imageObj,
width: imageObj.width,
height: imageObj.height,
draggable: false,
});
const scaleX = containerWidth / imageObj.width;
const scaleY = containerHeight / imageObj.height;
konvaImage.scale({ x: scaleX, y: scaleY });
imageConfig.value = konvaImage.getAttrs();
layer.value.getNode().batchDraw();
};
imageObj.src = e.target.result;
};
reader.readAsDataURL(event.target.files[0]);
};
let isDrawing = false;
let startX, startY;
const startDrawing = (e) => {
const pos = e.target.getStage().getPointerPosition();
startX = pos.x;
startY = pos.y;
isDrawing = true;
newRect.value = {
x: startX,
y: startY,
width: 0,
height: 0,
fill: 'rgba(255,0,0,0.5)',
id: `rect-${Date.now()}`,
};
};
const updateDrawing = (e) => {
if (!isDrawing) return;
const stage = e.target.getStage();
const pos = stage.getPointerPosition();
const width = Math.abs(pos.x - startX);
const height = Math.abs(pos.y - startY);
newRect.value.x = pos.x > startX ? startX : pos.x;
newRect.value.y = pos.y > startY ? startY : pos.y;
newRect.value.width = width;
newRect.value.height = height;
layer.value.getNode().batchDraw();
};
const finishDrawing = () => {
if (!isDrawing) return;
isDrawing = false;
rectangles.push(newRect.value);
newRect.value = null;
layer.value.getNode().batchDraw();
};
onMounted(() => {
if (stage.value && layer.value) {
layer.value.getNode().batchDraw();
}
});
return {
containerWidth,
containerHeight,
stage,
layer,
imageConfig,
handleImageUpload,
rectangles,
newRect,
startDrawing,
updateDrawing,
finishDrawing,
};
},
};
</script>
<style>
#canvas-container {
border: 1px solid #ccc;
width: 600px;
height: 400px;
overflow: hidden;
}
</style>
4. Integrate the Component in Your App
Update your App.vue (or another parent component) to include the ImageAnnotationKonva component:
<template>
<div id="app">
<ImageAnnotationKonva />
</div>
</template>
<script>
import ImageAnnotationKonva from './components/ImageAnnotationKonva.vue';
export default {
name: 'App',
components: {
ImageAnnotationKonva,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Explanation
-
File Upload: This component allows users to upload an image, which is then drawn onto the Konva canvas.
-
Konva.js Basics: We create a Stage, Layer, and use Image and Rect components to draw on the canvas.
-
Mouse Events:
startDrawing: Initializes the drawing when the mouse is pressed.
updateDrawing: Resizes the rectangle as the mouse moves.
finishDrawing: Completes drawing when the mouse is released, adding the rectangle to our reactive rectangles array.
-
Responsive Canvas: The image is rescaled according to the dimensions of the container, and all drawing operations respect this scaling.
This setup can be enhanced further with features like multiple rectangle management, enhanced UI/UX, and additional functionality like saving or exporting annotations.