vue实现白板
Vue 实现白板功能
使用 Vue 实现白板功能可以通过结合 HTML5 的 Canvas 和 Vue 的响应式特性来完成。以下是实现白板功能的核心步骤。
初始化 Canvas
在 Vue 组件中创建一个 Canvas 元素,并设置其宽高以适应白板需求。通过 ref 获取 Canvas 的 DOM 节点,并初始化绘图上下文。
<template>
<div>
<canvas ref="whiteboard" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.ctx = this.$refs.whiteboard.getContext('2d');
this.$refs.whiteboard.width = window.innerWidth;
this.$refs.whiteboard.height = window.innerHeight;
}
}
</script>
实现绘图逻辑
通过监听鼠标事件(mousedown、mousemove、mouseup)来实现绘图功能。记录鼠标的坐标并绘制线条。
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0
};
},
methods: {
startDrawing(e) {
this.isDrawing = true;
[this.lastX, this.lastY] = [e.offsetX, 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.stroke();
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
},
stopDrawing() {
this.isDrawing = false;
}
}
添加画笔样式
可以通过调整 ctx 的属性来设置画笔的颜色、粗细等样式。
mounted() {
this.ctx = this.$refs.whiteboard.getContext('2d');
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 5;
this.ctx.lineCap = 'round';
}
实现清除功能
添加一个清除按钮,通过调用 clearRect 方法清除画布内容。
<button @click="clearCanvas">清除</button>
methods: {
clearCanvas() {
this.ctx.clearRect(0, 0, this.$refs.whiteboard.width, this.$refs.whiteboard.height);
}
}
支持触屏设备
通过监听 touchstart、touchmove 和 touchend 事件,使白板在移动设备上也能使用。
<canvas
ref="whiteboard"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="stopDrawing"
></canvas>
methods: {
handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const rect = e.target.getBoundingClientRect();
this.startDrawing({
offsetX: touch.clientX - rect.left,
offsetY: touch.clientY - rect.top
});
},
handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const rect = e.target.getBoundingClientRect();
this.draw({
offsetX: touch.clientX - rect.left,
offsetY: touch.clientY - rect.top
});
}
}
保存白板内容
通过将 Canvas 转换为图像(如 PNG 或 JPEG)实现保存功能。
<button @click="saveCanvas">保存</button>
methods: {
saveCanvas() {
const link = document.createElement('a');
link.download = 'whiteboard.png';
link.href = this.$refs.whiteboard.toDataURL('image/png');
link.click();
}
}
优化与扩展
- 撤销/重做功能:使用数组记录绘图动作,通过操作数组实现撤销和重做。
- 多色画笔:添加颜色选择器,动态调整
ctx.strokeStyle。 - 实时协作:结合 WebSocket 实现多用户协同绘图。
通过以上步骤,可以在 Vue 中实现一个基础的白板功能,并根据需求进一步扩展。







