vue实现添加笔
Vue实现添加笔功能
在Vue中实现添加笔功能,可以通过结合Canvas绘图API和Vue的响应式特性来完成。以下是一个简单的实现方法:
创建Vue组件
<template>
<div>
<canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"></canvas>
<button @click="clearCanvas">清除</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0
}
},
mounted() {
this.ctx = this.$refs.canvas.getContext('2d')
this.resizeCanvas()
window.addEventListener('resize', this.resizeCanvas)
},
methods: {
resizeCanvas() {
this.$refs.canvas.width = window.innerWidth
this.$refs.canvas.height = window.innerHeight
},
startDrawing(e) {
this.isDrawing = true
this.lastX = e.offsetX
this.lastY = e.offsetY
},
draw(e) {
if (!this.isDrawing) return
this.ctx.beginPath()
this.ctx.moveTo(this.lastX, this.lastY)
this.ctx.lineTo(e.offsetX, e.offsetY)
this.ctx.strokeStyle = '#000000'
this.ctx.lineWidth = 5
this.ctx.stroke()
this.lastX = e.offsetX
this.lastY = e.offsetY
},
stopDrawing() {
this.isDrawing = false
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height)
}
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeCanvas)
}
}
</script>
添加笔触样式选项
可以通过添加数据属性和方法来实现不同的笔触样式:
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
color: '#000000',
lineWidth: 5,
lineCap: 'round'
}
},
methods: {
changeColor(newColor) {
this.color = newColor
},
changeWidth(newWidth) {
this.lineWidth = newWidth
},
changeLineCap(newCap) {
this.lineCap = newCap
},
draw(e) {
if (!this.isDrawing) return
this.ctx.beginPath()
this.ctx.moveTo(this.lastX, this.lastY)
this.ctx.lineTo(e.offsetX, e.offsetY)
this.ctx.strokeStyle = this.color
this.ctx.lineWidth = this.lineWidth
this.ctx.lineCap = this.lineCap
this.ctx.stroke()
this.lastX = e.offsetX
this.lastY = e.offsetY
}
}
添加触摸屏支持
为了支持移动设备,可以添加触摸事件:
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="stopDrawing"
></canvas>
methods: {
handleTouchStart(e) {
e.preventDefault()
const touch = e.touches[0]
const mouseEvent = {
offsetX: touch.clientX - this.$refs.canvas.offsetLeft,
offsetY: touch.clientY - this.$refs.canvas.offsetTop
}
this.startDrawing(mouseEvent)
},
handleTouchMove(e) {
e.preventDefault()
const touch = e.touches[0]
const mouseEvent = {
offsetX: touch.clientX - this.$refs.canvas.offsetLeft,
offsetY: touch.clientY - this.$refs.canvas.offsetTop
}
this.draw(mouseEvent)
}
}
保存绘图功能
可以添加保存绘图为图片的功能:

methods: {
saveDrawing() {
const dataURL = this.$refs.canvas.toDataURL('image/png')
const link = document.createElement('a')
link.download = 'drawing.png'
link.href = dataURL
link.click()
}
}
这个实现提供了基本的绘图功能,可以根据需要进一步扩展,如添加橡皮擦、撤销重做等功能。






