vue进行图片标注,放大,缩小并存储标注数据
时间: 2024-04-23 07:03:14 浏览: 14
要实现图片标注、放大、缩小并存储标注数据,可以使用以下步骤:
1. 加载图片:使用Vue的`<img>`标签加载图片。
2. 标注图片:使用Vue的`<canvas>`标签绘制图片,通过鼠标事件监听用户的标注操作,将标注数据存储在Vue的数据中。
3. 放大、缩小:通过CSS的`transform`属性实现图片的放大、缩小效果,同时也需要更新绘制标注的画布大小和坐标。
4. 存储标注数据:将标注数据存储在本地存储或后端数据库中,可以使用Vue的`localStorage`或`axios`库实现。
下面是一个简单的示例代码:
```
<template>
<div>
<img ref="image" :src="imageUrl" @load="onImageLoad">
<div ref="canvasWrapper" class="canvas-wrapper">
<canvas ref="canvas" @mousedown="onMouseDown" @mousemove="onMouseMove" @mouseup="onMouseUp"></canvas>
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://image.url',
imageWidth: 0,
imageHeight: 0,
canvasWidth: 0,
canvasHeight: 0,
canvasLeft: 0,
canvasTop: 0,
isMouseDown: false,
startX: 0,
startY: 0,
annotations: []
}
},
methods: {
onImageLoad() {
this.imageWidth = this.$refs.image.width
this.imageHeight = this.$refs.image.height
this.canvasWidth = this.imageWidth
this.canvasHeight = this.imageHeight
this.$refs.canvas.width = this.canvasWidth
this.$refs.canvas.height = this.canvasHeight
this.canvasLeft = this.$refs.canvasWrapper.offsetLeft
this.canvasTop = this.$refs.canvasWrapper.offsetTop
this.drawAnnotations()
},
onMouseDown(event) {
this.isMouseDown = true
this.startX = event.pageX - this.canvasLeft
this.startY = event.pageY - this.canvasTop
},
onMouseMove(event) {
if (this.isMouseDown) {
const x = event.pageX - this.canvasLeft
const y = event.pageY - this.canvasTop
const width = x - this.startX
const height = y - this.startY
const annotation = { x: this.startX, y: this.startY, width, height }
this.annotations.push(annotation)
this.drawAnnotations()
}
},
onMouseUp() {
this.isMouseDown = false
},
drawAnnotations() {
const ctx = this.$refs.canvas.getContext('2d')
ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
ctx.drawImage(this.$refs.image, 0, 0, this.imageWidth, this.imageHeight)
for (const annotation of this.annotations) {
ctx.strokeRect(annotation.x, annotation.y, annotation.width, annotation.height)
}
},
zoomIn() {
this.canvasWidth *= 1.2
this.canvasHeight *= 1.2
this.$refs.canvas.width = this.canvasWidth
this.$refs.canvas.height = this.canvasHeight
this.drawAnnotations()
},
zoomOut() {
this.canvasWidth /= 1.2
this.canvasHeight /= 1.2
this.$refs.canvas.width = this.canvasWidth
this.$refs.canvas.height = this.canvasHeight
this.drawAnnotations()
},
saveAnnotations() {
localStorage.setItem('annotations', JSON.stringify(this.annotations))
},
loadAnnotations() {
const annotations = JSON.parse(localStorage.getItem('annotations'))
if (annotations) {
this.annotations = annotations
this.drawAnnotations()
}
}
}
}
</script>
<style scoped>
.canvas-wrapper {
position: relative;
overflow: hidden;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
```