uniapp 画板
uniapp 实现画板功能的方法
在 uniapp 中实现画板功能,可以通过 canvas 组件结合触摸事件来完成。以下是一个基本的实现方案:
基本画板实现
在 template 中添加 canvas 组件:
<canvas canvas-id="myCanvas"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
style="width: 100%; height: 500px; background-color: #f8f8f8;">
</canvas>
在 script 中实现绘图逻辑:
export default {
data() {
return {
points: [],
isDrawing: false
}
},
methods: {
touchStart(e) {
this.isDrawing = true
const point = {
x: e.touches[0].x,
y: e.touches[0].y
}
this.points.push(point)
this.draw()
},
touchMove(e) {
if (!this.isDrawing) return
const point = {
x: e.touches[0].x,
y: e.touches[0].y
}
this.points.push(point)
this.draw()
},
touchEnd() {
this.isDrawing = false
this.points = []
},
draw() {
const ctx = uni.createCanvasContext('myCanvas', this)
ctx.setStrokeStyle('#000000')
ctx.setLineWidth(5)
ctx.setLineCap('round')
ctx.setLineJoin('round')
ctx.beginPath()
ctx.moveTo(this.points[0].x, this.points[0].y)
for (let i = 1; i < this.points.length; i++) {
ctx.lineTo(this.points[i].x, this.points[i].y)
}
ctx.stroke()
ctx.draw(true)
}
}
}
功能扩展
添加颜色选择功能:
<view class="color-picker">
<view v-for="color in colors" :key="color"
:style="{backgroundColor: color}"
@click="selectColor(color)">
</view>
</view>
在 data 中添加颜色数组并实现选择方法:
data() {
return {
colors: ['#000000', '#ff0000', '#00ff00', '#0000ff', '#ffff00'],
currentColor: '#000000'
}
},
methods: {
selectColor(color) {
this.currentColor = color
}
}
修改 draw 方法中的颜色设置:
ctx.setStrokeStyle(this.currentColor)
橡皮擦功能实现
添加橡皮擦按钮:
<button @click="toggleEraser">橡皮擦</button>
在 data 中添加橡皮擦状态并实现切换方法:
data() {
return {
isEraser: false
}
},
methods: {
toggleEraser() {
this.isEraser = !this.isEraser
}
}
修改 draw 方法:
if (this.isEraser) {
ctx.setStrokeStyle('#f8f8f8')
ctx.setLineWidth(20)
} else {
ctx.setStrokeStyle(this.currentColor)
ctx.setLineWidth(5)
}
保存画布内容
添加保存按钮:
<button @click="saveCanvas">保存</button>
实现保存方法:
methods: {
saveCanvas() {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({ title: '保存成功' })
}
})
}
})
}
}
性能优化
对于复杂绘图,可以采用增量绘制方式,只绘制最新路径段:
touchMove(e) {
if (!this.isDrawing) return
const ctx = uni.createCanvasContext('myCanvas', this)
ctx.setStrokeStyle(this.isEraser ? '#f8f8f8' : this.currentColor)
ctx.setLineWidth(this.isEraser ? 20 : 5)
ctx.setLineCap('round')
ctx.setLineJoin('round')
const startPoint = this.points[this.points.length - 1]
const endPoint = {
x: e.touches[0].x,
y: e.touches[0].y
}
ctx.beginPath()
ctx.moveTo(startPoint.x, startPoint.y)
ctx.lineTo(endPoint.x, endPoint.y)
ctx.stroke()
ctx.draw(true)
this.points.push(endPoint)
}
跨平台注意事项
不同平台 canvas 实现有差异,建议进行平台判断:
const systemInfo = uni.getSystemInfoSync()
if (systemInfo.platform === 'android') {
// Android 特定处理
} else if (systemInfo.platform === 'ios') {
// iOS 特定处理
}
以上方案提供了 uniapp 中实现画板功能的基本方法,可根据实际需求进一步扩展功能。







