this code work ok can you optimize and make it better <template> <div> <input…
- User
this code work ok can you optimize and make it better
- Assistant
this code work ok can you optimize and make it better
The code already largely follows best practices and is nicely structured with Vue.js. However, I can suggest some minor improvements to make it slightly more optimized and maintainable:
Reduce Repeated Canvas Context Calls: Instead of calling this.$refs.canvas.getContext('2d') multiple times, store the context in a variable during setupCanvas() and reuse it. This can help avoid redundant DOM lookups.
Clean Up Event Handling: Consider using separate functions for updating the state based on mouse actions to make the code cleaner.
Improve Rectangles Storage: Normalize rectangle data and keep it scaled with respect to canvas dimension changes and transformations.
Replace new Image() with Image() Constructor: Directly using Image() is often more concise.
Cleanup Canvas in Lifecycle Methods: Ensure that canvas dimensions are properly reset in lifecycle methods like beforeDestroy if necessary.
Optimize Mouse Coordinate Calculations: Leverage utility functions to calculate mouse coordinates in relation to the canvas, avoiding repeated calculations.
Here is an updated version incorporating these suggestions:
<template>
<div>
<input type="file" accept="image/*" @change="loadImage" />
<canvas ref="canvas" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp" @wheel="handleWheel"></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,
ctx: null,
isDrawing: false,
isDragging: false,
isResizing: false,
startX: 0,
startY: 0,
currentX: 0,
currentY: 0,
activeRectIndex: null,
rectangles: [],
activeHandle: null,
handleSize: 8,
scale: 1,
minScale: 0.5,
maxScale: 3
};
},
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.setupCanvas();
};
img.src = src;
},
setupCanvas() {
const canvas = this.$refs.canvas;
canvas.width = this.image.width * this.scale;
canvas.height = this.image.height * this.scale;
this.ctx = canvas.getContext('2d');
this.drawImage();
},
drawImage() {
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
this.ctx.drawImage(this.image, 0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
this.drawRectangles();
},
drawRectangles() {
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 2 / this.scale;
this.rectangles.forEach((rect, index) => {
const rectX = rect.x * this.$refs.canvas.width;
const rectY = rect.y * this.$refs.canvas.height;
const rectWidth = rect.width * this.$refs.canvas.width;
const rectHeight = rect.height * this.$refs.canvas.height;
this.ctx.strokeRect(rectX, rectY, rectWidth, rectHeight);
if (index === this.activeRectIndex) {
this.drawHandles(rectX, rectY, rectWidth, rectHeight);
}
});
},
drawHandles(x, y, width, height) {
const halfSize = (this.handleSize / 2) / this.scale;
const positions = [
{ x: x - halfSize, y: y - halfSize },
{ x: x + width - halfSize, y: y - halfSize },
{ x: x - halfSize, y: y + height - halfSize },
{ x: x + width - halfSize, y: y + height - halfSize },
{ x: x + width / 2 - halfSize, y: y - halfSize },
{ x: x + width / 2 - halfSize, y: y + height - halfSize },
{ x: x - halfSize, y: y + height / 2 - halfSize },
{ x: x + width - halfSize, y: y + height / 2 - halfSize }
];
this.ctx.fillStyle = 'blue';
positions.forEach(pos => {
this.ctx.fillRect(pos.x, pos.y, this.handleSize / this.scale, this.handleSize / this.scale);
});
},
handleWheel(event) {
event.preventDefault();
const zoomFactor = 1.1;
if (event.deltaY < 0) {
this.scale = Math.min(this.scale * zoomFactor, this.maxScale);
} else {
this.scale = Math.max(this.scale / zoomFactor, this.minScale);
}
this.setupCanvas();
},
handleMouseDown(event) {
const { mouseX, mouseY } = this.getMouseCoords(event);
this.activeRectIndex = this.hitTest(mouseX, mouseY);
if (this.activeRectIndex !== null) {
const handleHit = this.hitTestHandles(mouseX, mouseY);
if (handleHit) {
this.isResizing = true;
this.activeHandle = handleHit;
this.startX = mouseX;
this.startY = mouseY;
} else {
this.isDragging = true;
this.startX = mouseX;
this.startY = mouseY;
}
} else {
this.isDrawing = true;
this.startX = mouseX;
this.startY = mouseY;
}
},
handleMouseMove(event) {
if (!(this.isDrawing || this.isDragging || this.isResizing)) return;
const { mouseX, mouseY } = this.getMouseCoords(event);
this.currentX = mouseX;
this.currentY = mouseY;
if (this.isResizing && this.activeRectIndex !== null) {
this.resizeRectangle();
} else if (this.isDragging && this.activeRectIndex !== null) {
this.moveRectangle();
}
this.drawImage();
if (this.isDrawing) {
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 2 / this.scale;
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);
this.ctx.strokeRect(x, y, width, height);
}
},
handleMouseUp() {
if (this.isDrawing) {
const canvas = this.$refs.canvas;
const x = Math.min(this.startX, this.currentX) / canvas.width;
const y = Math.min(this.startY, this.currentY) / canvas.height;
const rectWidth = Math.abs(this.currentX - this.startX) / canvas.width;
const rectHeight = Math.abs(this.currentY - this.startY) / canvas.height;
this.rectangles.push({ x, y, width: rectWidth, height: rectHeight });
this.isDrawing = false;
}
if (this.isDragging) {
this.isDragging = false;
}
if (this.isResizing) {
this.isResizing = false;
this.activeHandle = null;
}
},
hitTest(x, y) {
for (let i = 0; i < this.rectangles.length; i++) {
const rect = this.rectangles[i];
const canvas = this.$refs.canvas;
const rectX = rect.x * canvas.width;
const rectY = rect.y * canvas.height;
const rectWidth = rect.width * canvas.width;
const rectHeight = rect.height * canvas.height;
if (x > rectX && x < rectX + rectWidth && y > rectY && y < rectY + rectHeight) {
return i;
}
}
return null;
},
hitTestHandles(x, y) {
const rect = this.rectangles[this.activeRectIndex];
const canvas = this.$refs.canvas;
const rectX = rect.x * canvas.width;
const rectY = rect.y * canvas.height;
const rectWidth = rect.width * canvas.width;
const rectHeight = rect.height * canvas.height;
const halfSize = this.handleSize / 2;
const positions = [
{ x: rectX - halfSize, y: rectY - halfSize, handle: 'top-left' },
{ x: rectX + rectWidth - halfSize, y: rectY - halfSize, handle: 'top-right' },
{ x: rectX - halfSize, y: rectY + rectHeight - halfSize, handle: 'bottom-left' },
{ x: rectX + rectWidth - halfSize, y: rectY + rectHeight - halfSize, handle: 'bottom-right' },
{ x: rectX + rectWidth / 2 - halfSize, y: rectY - halfSize, handle: 'top-middle' },
{ x: rectX + rectWidth / 2 - halfSize, y: rectY + rectHeight - halfSize, handle: 'bottom-middle' },
{ x: rectX - halfSize, y: rectY + rectHeight / 2 - halfSize, handle: 'middle-left' },
{ x: rectX + rectWidth - halfSize, y: rectY + rectHeight / 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;
},
resizeRectangle() {
const rect = this.rectangles[this.activeRectIndex];
const canvas = this.$refs.canvas;
const deltaX = (this.currentX - this.startX) / canvas.width;
const deltaY = (this.currentY - this.startY) / canvas.height;
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 = this.currentX;
this.startY = this.currentY;
},
moveRectangle() {
const rect = this.rectangles[this.activeRectIndex];
const canvas = this.$refs.canvas;
const offsetX = this.currentX - this.startX;
const offsetY = this.currentY - this.startY;
rect.x += offsetX / canvas.width;
rect.y += offsetY / canvas.height;
this.startX = this.currentX;
this.startY = this.currentY;
},
deleteRectangle(index) {
this.rectangles.splice(index, 1);
this.drawImage();
},
getMouseCoords(event) {
const rect = this.$refs.canvas.getBoundingClientRect();
const mouseX = (event.clientX - rect.left) * (this.$refs.canvas.width / rect.width);
const mouseY = (event.clientY - rect.top) * (this.$refs.canvas.height / rect.height);
return { mouseX, mouseY };
}
}
};
</script>
<style>
canvas {
border: 1px solid black;
max-width: 100%;
height: auto;
cursor: default;
}
</style>
These optimizations clean up the code, making it slightly more efficient and modular. Keep in mind these suggestions also aim to set up good practices for future scalability.