Certainly! I'll regenerate the entire Vue component with your described functionality, ensuring the code is optimized and any potential errors related to undefined values are mitigated. The component will handle image loading, drawing rectangles, dragging, resizing, and deleting rectangles interactively. Here's how it could be structured:
<template>
<div>
<input type="file" accept="image/*" @change="loadImage" />
<canvas
ref="canvas"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
></canvas>
<div v-if="rectangles.length">
<h3>Rectangles:</h3>
<ul>
<li v-for="(rect, index) in rectangles" :key="index">
Rectangle {{ index + 1 }}:
(x: {{ rect.x.toFixed(2) }}, y: {{ rect.y.toFixed(2) }},
width: {{ rect.width.toFixed(2) }}, height: {{ rect.height.toFixed(2) }})
<button @click="deleteRectangle(index)">Delete</button>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
image: null,
actionState: null,
startX: 0,
startY: 0,
currentX: 0,
currentY: 0,
activeRectIndex: null,
rectangles: [],
activeHandle: null,
handleSize: 8,
};
},
methods: {
loadImage(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
this.image = img;
this.setupCanvas();
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
},
setupCanvas() {
const canvas = this.$refs.canvas;
canvas.width = this.image.width;
canvas.height = this.image.height;
this.drawImage();
},
drawImage() {
const ctx = this.$refs.canvas.getContext('2d');
ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
ctx.drawImage(this.image, 0, 0);
this.drawRectangles(ctx);
},
drawRectangles(ctx) {
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
for (const [index, rect] of this.rectangles.entries()) {
const { trueX, trueY, trueWidth, trueHeight } = this.getNormalizedRect(rect);
ctx.strokeRect(trueX, trueY, trueWidth, trueHeight);
if (index === this.activeRectIndex) {
this.drawHandles(ctx, trueX, trueY, trueWidth, trueHeight);
}
}
},
getNormalizedRect(rect) {
const canvasWidth = this.$refs.canvas.width;
const canvasHeight = this.$refs.canvas.height;
return {
trueX: rect.x * canvasWidth,
trueY: rect.y * canvasHeight,
trueWidth: rect.width * canvasWidth,
trueHeight: rect.height * canvasHeight,
};
},
drawHandles(ctx, x, y, width, height) {
const halfSize = this.handleSize / 2;
const positions = [
[x - halfSize, y - halfSize],
[x + width - halfSize, y - halfSize],
[x - halfSize, y + height - halfSize],
[x + width - halfSize, y + height - halfSize],
[x + width / 2 - halfSize, y - halfSize],
[x + width / 2 - halfSize, y + height - halfSize],
[x - halfSize, y + height / 2 - halfSize],
[x + width - halfSize, y + height / 2 - halfSize],
];
ctx.fillStyle = 'blue';
for (const [px, py] of positions) {
ctx.fillRect(px, py, this.handleSize, this.handleSize);
}
},
handleMouseDown(event) {
const { x, y } = this.getCanvasCoordinates(event);
this.activeRectIndex = this.hitTest(x, y);
if (this.activeRectIndex !== null) {
const handle = this.hitTestHandles(x, y);
if (handle) {
this.actionState = 'resizing';
this.activeHandle = handle;
} else {
this.actionState = 'dragging';
}
} else {
this.actionState = 'drawing';
this.startX = x;
this.startY = y;
}
this.startX = x;
this.startY = y;
},
handleMouseMove(event) {
if (!this.actionState) return;
const { x, y } = this.getCanvasCoordinates(event);
this.currentX = x;
this.currentY = y;
this.drawImage();
if (this.actionState === 'drawing') {
this.drawCurrentRectangle();
} else if (this.actionState === 'dragging') {
this.moveRectangle(x, y);
} else if (this.actionState === 'resizing') {
this.resizeRectangle(x, y);
}
},
drawCurrentRectangle() {
const ctx = this.$refs.canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(
Math.min(this.startX, this.currentX),
Math.min(this.startY, this.currentY),
Math.abs(this.currentX - this.startX),
Math.abs(this.currentY - this.startY)
);
},
handleMouseUp() {
if (this.actionState === 'drawing') {
this.endDraw();
}
this.actionState = null;
this.activeHandle = null;
},
endDraw() {
const canvasWidth = this.$refs.canvas.width;
const canvasHeight = this.$refs.canvas.height;
const x = Math.min(this.startX, this.currentX) / canvasWidth;
const y = Math.min(this.startY, this.currentY) / canvasHeight;
const width = Math.abs(this.currentX - this.startX) / canvasWidth;
const height = Math.abs(this.currentY - this.startY) / canvasHeight;
if (width > 0 && height > 0) {
this.rectangles.push({ x, y, width, height });
}
},
getCanvasCoordinates(event) {
const rect = this.$refs.canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * (this.$refs.canvas.width / rect.width),
y: (event.clientY - rect.top) * (this.$refs.canvas.height / rect.height),
};
},
hitTest(x, y) {
return this.rectangles.findIndex((rect) => {
const { trueX, trueY, trueWidth, trueHeight } = this.getNormalizedRect(rect);
return x >= trueX && x <= trueX + trueWidth && y >= trueY && y <= trueY + trueHeight;
});
},
hitTestHandles(x, y) {
if (this.activeRectIndex === null) return null;
const { trueX, trueY, trueWidth, trueHeight } = this.getNormalizedRect(this.rectangles[this.activeRectIndex]);
const halfSize = this.handleSize / 2;
const positions = [
{ x: trueX - halfSize, y: trueY - halfSize, handle: 'top-left' },
{ x: trueX + trueWidth - halfSize, y: trueY - halfSize, handle: 'top-right' },
{ x: trueX - halfSize, y: trueY + trueHeight - halfSize, handle: 'bottom-left' },
{ x: trueX + trueWidth - halfSize, y: trueY + trueHeight - halfSize, handle: 'bottom-right' },
{ x: trueX + trueWidth / 2 - halfSize, y: trueY - halfSize, handle: 'top-middle' },
{ x: trueX + trueWidth / 2 - halfSize, y: trueY + trueHeight - halfSize, handle: 'bottom-middle' },
{ x: trueX - halfSize, y: trueY + trueHeight / 2 - halfSize, handle: 'middle-left' },
{ x: trueX + trueWidth - halfSize, y: trueY + trueHeight / 2 - halfSize, handle: 'middle-right' },
];
for (const pos of positions) {
if (x >= pos.x && x <= pos.x + this.handleSize && y >= pos.y && y <= pos.y + this.handleSize) {
return pos.handle;
}
}
return null;
},
moveRectangle(x, y) {
if (this.activeRectIndex === null) return;
const rect = this.rectangles[this.activeRectIndex];
rect.x += (x - this.startX) / this.$refs.canvas.width;
rect.y += (y - this.startY) / this.$refs.canvas.height;
this.startX = x;
this.startY = y;
},
resizeRectangle(x, y) {
if (this.activeRectIndex === null || !this.activeHandle) return;
const rect = this.rectangles[this.activeRectIndex];
const deltaX = (x - this.startX) / this.$refs.canvas.width;
const deltaY = (y - this.startY) / this.$refs.canvas.height;
// Adjust the rectangle size and position based on the handle
if (this.activeHandle.includes('left')) {
rect.x += deltaX;
rect.width -= deltaX;
}
if (this.activeHandle.includes('right')) {
rect.width += deltaX;
}
if (this.activeHandle.includes('top')) {
rect.y += deltaY;
rect.height -= deltaY;
}
if (this.activeHandle.includes('bottom')) {
rect.height += deltaY;
}
this.startX = x;
this.startY = y;
},
deleteRectangle(index) {
this.rectangles.splice(index, 1);
this.drawImage();
},
},
};
</script>
<style>
canvas {
border: 1px solid black;
max-width: 100%;
height: auto;
cursor: default;
}
</style>
Explanation
-
Image Loading: The image is loaded from a file input and displayed on a canvas.
-
Drawing: When the user starts drawing, a rectangle is drawn interactively on the canvas.
-
Dragging and Resizing: Existing rectangles can be selected, dragged, or resized using mouse operations.
-
Deleting: Rectangles can be removed from a list of drawn rectangles.
-
Error Avoidance: Checks are included to ensure properties such as rectangle dimensions are accessed safely, avoiding undefined values.
-
Improved State Management: State transitions are managed carefully with actionState to reduce complexity and potential errors when interacting with the canvas.
This should provide a more robust, clean interface for interactive canvas drawing in Vue. Adjust any canvas size or styling as necessary to fit into your application.