To draw rectangles on an image within a canvas while ensuring that the image stays visible and correctly positioned, it’s essential to properly manage the canvas and image dimensions, as well as correctly handle mouse events to draw and update the rectangle. Here's a complete approach to achieve this:
Approach
- Load and Draw Image: Load the image from an input file and draw it onto a canvas.
- Track Mouse Events: Use
mousedown, mousemove, and mouseup to handle drawing rectangles.
- Redraw Canvas: Continuously redraw the image and the current rectangle during drawing.
Full Implementation in Vue.js
Here's a component that allows you to upload an image, draw rectangles on it, and get normalized coordinates:
<template>
<div>
<input type="file" accept="image/*" @change="loadImage" />
<canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="endDrawing"></canvas>
<div v-if="normalizedCoords">
Normalized Coordinates: ({{ normalizedCoords[0].toFixed(2) }}, {{ normalizedCoords[1].toFixed(2) }}, {{ normalizedCoords[2].toFixed(2) }}, {{ normalizedCoords[3].toFixed(2) }})
</div>
</div>
</template>
<script>
export default {
data() {
return {
image: null,
isDrawing: false,
startX: 0,
startY: 0,
currentX: 0,
currentY: 0,
normalizedCoords: null,
};
},
methods: {
loadImage(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => this.createImage(e.target.result);
reader.readAsDataURL(file);
},
createImage(src) {
const img = new Image();
img.onload = () => {
this.image = img;
this.drawImageOnCanvas();
};
img.src = src;
},
drawImageOnCanvas() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
// Set canvas dimensions to image dimensions
canvas.width = this.image.width;
canvas.height = this.image.height;
// Draw the image on the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this.image, 0, 0, canvas.width, canvas.height);
},
startDrawing(event) {
const rect = this.$refs.canvas.getBoundingClientRect();
this.isDrawing = true;
this.startX = event.clientX - rect.left;
this.startY = event.clientY - rect.top;
},
draw(event) {
if (!this.isDrawing) return;
const rect = this.$refs.canvas.getBoundingClientRect();
this.currentX = event.clientX - rect.left;
this.currentY = event.clientY - rect.top;
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
// Redraw image and current rectangle
this.drawImageOnCanvas();
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
const [x, y, width, height] = this.getRectangleDimensions();
ctx.strokeRect(x, y, width, height);
},
endDrawing() {
if (!this.isDrawing) return;
this.isDrawing = false;
// Calculate and display normalized coordinates
this.normalizeCoordinates();
},
getRectangleDimensions() {
const x = Math.min(this.startX, this.currentX);
const y = Math.min(this.startY, this.currentY);
const width = Math.abs(this.currentX - this.startX);
const height = Math.abs(this.currentY - this.startY);
return [x, y, width, height];
},
normalizeCoordinates() {
const canvas = this.$refs.canvas;
const width = canvas.width;
const height = canvas.height;
// Calculate normalized coordinates
const x1 = Math.min(this.startX, this.currentX) / width;
const y1 = Math.min(this.startY, this.currentY) / height;
const x2 = Math.max(this.startX, this.currentX) / width;
const y2 = Math.max(this.startY, this.currentY) / height;
this.normalizedCoords = [x1, y1, x2, y2];
},
},
};
</script>
<style>
canvas {
border: 1px solid black;
max-width: 100%;
height: auto;
}
</style>
Key Components of the Solution
-
Image Handling: The image is loaded and drawn onto a canvas using the createImage() and drawImageOnCanvas() methods.
-
Mouse Event Handling: The startDrawing, draw, and endDrawing methods handle the user's interaction. They calculate the positions and dimensions of the rectangle relative to the canvas.
-
Rectangle Drawing: The rectangle is drawn on top of the image each time draw is called. This action is triggered during the mousemove event while drawing is active.
-
Normalized Coordinates: Once drawing is finished, the rectangle's coordinates are normalized, providing values between 0 and 1, relative to the size of the canvas/image.
This setup ensures that the rectangle is always drawn over the image according to the user's input. If you're encountering issues with the drawing, ensure the canvas's dimensions match the image's dimensions, as this is crucial for correct coordinate handling.