vue实现画板功能
Vue 实现画板功能
核心实现思路
通过 Vue 的指令和事件绑定结合 HTML5 的 Canvas API 实现画板功能。主要利用 mousedown、mousemove 和 mouseup 事件跟踪绘制路径。
基础画板实现
<template>
<div>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
canvas: null,
ctx: null
}
},
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.resizeCanvas();
window.addEventListener('resize', this.resizeCanvas);
},
methods: {
resizeCanvas() {
this.canvas.width = window.innerWidth - 20;
this.canvas.height = window.innerHeight - 20;
},
startDrawing(e) {
this.isDrawing = true;
this.ctx.beginPath();
this.ctx.moveTo(e.offsetX, e.offsetY);
},
draw(e) {
if (!this.isDrawing) return;
this.ctx.lineTo(e.offsetX, e.offsetY);
this.ctx.stroke();
},
stopDrawing() {
this.isDrawing = false;
}
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeCanvas);
}
}
</script>
<style scoped>
canvas {
border: 1px solid #000;
background-color: white;
}
</style>
功能扩展实现
添加画笔颜色选择
<input type="color" v-model="brushColor" @change="updateBrushColor">
data() {
return {
brushColor: '#000000'
}
},
methods: {
updateBrushColor() {
this.ctx.strokeStyle = this.brushColor;
}
}
调整画笔粗细
<input type="range" min="1" max="50" v-model="brushSize">
data() {
return {
brushSize: 5
}
},
methods: {
startDrawing(e) {
this.ctx.lineWidth = this.brushSize;
// ...原有代码
}
}
实现橡皮擦功能
methods: {
toggleEraser() {
this.isEraser = !this.isEraser;
this.ctx.globalCompositeOperation = this.isEraser
? 'destination-out'
: 'source-over';
}
}
保存画布内容
methods: {
saveCanvas() {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = this.canvas.toDataURL('image/png');
link.click();
}
}
触摸屏适配
<canvas
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="stopDrawing"
></canvas>
methods: {
handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = {
offsetX: touch.clientX - this.canvas.offsetLeft,
offsetY: touch.clientY - this.canvas.offsetTop
};
this.startDrawing(mouseEvent);
},
handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = {
offsetX: touch.clientX - this.canvas.offsetLeft,
offsetY: touch.clientY - this.canvas.offsetTop
};
this.draw(mouseEvent);
}
}
性能优化建议
- 使用
requestAnimationFrame优化绘制性能 - 实现双缓冲技术减少闪烁
- 添加撤销/重做功能时需要维护绘制历史栈
以上实现提供了完整的画板基础功能,可根据实际需求进一步扩展其他特性如形状绘制、文字添加等高级功能。







