vue用canvas实现图片编辑画矩形箭头多边形撤销
时间: 2023-07-12 08:38:02 浏览: 123
要实现这个功能,你可以使用 Vue.js 和 canvas 标签来创建一个图片编辑器。以下是一个简单的示例代码,可以用来实现在图片上绘制矩形、箭头和多边形,并支持撤销操作。
```vue
<template>
<div>
<canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="endDrawing"></canvas>
<button @click="undo">Undo</button>
</div>
</template>
<script>
export default {
data() {
return {
canvas: null,
ctx: null,
isDrawing: false,
startX: 0,
startY: 0,
endX: 0,
endY: 0,
shapes: []
}
},
mounted() {
this.canvas = this.$refs.canvas
this.ctx = this.canvas.getContext('2d')
const img = new Image()
img.src = 'your-image-src'
img.onload = () => {
this.canvas.width = img.width
this.canvas.height = img.height
this.ctx.drawImage(img, 0, 0)
}
},
methods: {
startDrawing(e) {
this.isDrawing = true
this.startX = e.clientX - this.canvas.offsetLeft
this.startY = e.clientY - this.canvas.offsetTop
this.shapes.push({ type: 'start', x: this.startX, y: this.startY })
},
draw(e) {
if (!this.isDrawing) return
this.endX = e.clientX - this.canvas.offsetLeft
this.endY = e.clientY - this.canvas.offsetTop
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.ctx.drawImage(this.$refs.canvas, 0, 0)
switch (this.shape) {
case 'rectangle':
this.ctx.strokeRect(this.startX, this.startY, this.endX - this.startX, this.endY - this.startY)
break
case 'arrow':
// draw arrow
break
case 'polygon':
// draw polygon
break
}
},
endDrawing() {
this.isDrawing = false
this.shapes.push({ type: this.shape, x: this.startX, y: this.startY, w: this.endX - this.startX, h: this.endY - this.startY })
},
undo() {
if (this.shapes.length === 0) return
const lastShape = this.shapes.pop()
if (lastShape.type === 'start') {
this.shapes.pop()
return
}
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.ctx.drawImage(this.$refs.canvas, 0, 0)
this.shapes.forEach(shape => {
switch (shape.type) {
case 'rectangle':
this.ctx.strokeRect(shape.x, shape.y, shape.w, shape.h)
break
case 'arrow':
// draw arrow
break
case 'polygon':
// draw polygon
break
}
})
}
}
}
</script>
```
这个示例中,我们在 canvas 标签上绑定了三个事件:mousedown、mousemove 和 mouseup。当用户按下鼠标左键时,我们会记录起始坐标,并将其添加到 shapes 数组中。在 mousemove 事件中,我们会实时更新结束坐标,并使用 strokeRect 方法画出一个矩形。在 mouseup 事件中,我们会将当前的形状类型和坐标信息添加到 shapes 数组中。
我们还添加了一个 undo 方法,用于撤销上一步操作。当用户点击撤销按钮时,我们会从 shapes 数组中取出最后一个元素,然后根据其类型和坐标信息重新绘制画布。
你可以根据这个示例,使用 canvas 的 API 来实现箭头、多边形等其他形状,并支持更多的操作和功能。
阅读全文