vue 移动端 涂鸦画板
时间: 2023-11-19 17:06:20 浏览: 228
以下是一个基于Vue的移动端涂鸦画板的实现方法:
1. 在Vue组件中,使用canvas元素创建画布,并设置画布的宽度和高度。
```html
<template>
<div class="canvas-container">
<canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
</div>
</template>
```
2. 在组件的data选项中,定义画布的宽度和高度,以及画笔的颜色和粗细。
```javascript
export default {
data() {
return {
canvasWidth: 300,
canvasHeight: 300,
brushColor: '#000000',
brushSize: 5,
isDrawing: false
}
}
}
```
3. 在组件的mounted钩子函数中,获取canvas元素和2D上下文,并添加touch事件监听器。
```javascript
export default {
mounted() {
const canvas = this.$refs.canvas
this.ctx = canvas.getContext('2d')
canvas.addEventListener('touchstart', this.handleTouchStart)
canvas.addEventListener('touchmove', this.handleTouchMove)
canvas.addEventListener('touchend', this.handleTouchEnd)
},
methods: {
handleTouchStart(e) {
this.isDrawing = true
const canvasX = e.changedTouches[0].clientX - e.target.parentNode.offsetLeft
const canvasY = e.changedTouches[0].clientY - e.target.parentNode.offsetTop
this.ctx.beginPath()
this.ctx.moveTo(canvasX, canvasY)
},
handleTouchMove(e) {
if (this.isDrawing) {
const canvasX = e.changedTouches[0].clientX - e.target.parentNode.offsetLeft
const canvasY = e.changedTouches[0].clientY - e.target.parentNode.offsetTop
this.ctx.lineTo(canvasX, canvasY)
this.ctx.strokeStyle = this.brushColor
this.ctx.lineWidth = this.brushSize
this.ctx.stroke()
}
},
handleTouchEnd() {
this.isDrawing = false
}
}
}
```
4. 在组件的template中,添加控制画笔颜色和粗细的按钮。
```html
<template>
<div class="canvas-container">
<canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
<div class="controls">
<button @click="brushColor = '#000000'">Black</button>
<button @click="brushColor = '#ff0000'">Red</button>
<button @click="brushColor = '#00ff00'">Green</button>
<button @click="brushColor = '#0000ff'">Blue</button>
<input type="range" v-model="brushSize" min="1" max="20">
</div>
</div>
</template>
```
阅读全文