vue实现画板
Vue 实现画板功能
实现一个基于 Vue 的画板功能可以通过 HTML5 的 Canvas API 结合 Vue 的响应式特性完成。以下是具体实现方法:
创建 Vue 项目并初始化画布
安装 Vue 3 项目(如未创建):
npm init vue@latest
在组件中引入 Canvas 元素:
<template>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
</template>
初始化画布上下文
在 setup 或 mounted 生命周期中初始化画布:
import { ref, onMounted } from 'vue';
const canvas = ref(null);
const isDrawing = ref(false);
onMounted(() => {
const ctx = canvas.value.getContext('2d');
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
});
实现绘图逻辑
定义绘图函数:

const startDrawing = (e) => {
isDrawing.value = true;
const ctx = canvas.value.getContext('2d');
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
};
const draw = (e) => {
if (!isDrawing.value) return;
const ctx = canvas.value.getContext('2d');
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
};
const stopDrawing = () => {
isDrawing.value = false;
};
添加画笔样式控制
在模板中添加颜色和粗细控制:
<input type="color" v-model="brushColor">
<input type="range" v-model="brushWidth" min="1" max="50">
更新绘图函数以响应样式变化:
const brushColor = ref('#000000');
const brushWidth = ref(5);
const draw = (e) => {
if (!isDrawing.value) return;
const ctx = canvas.value.getContext('2d');
ctx.lineWidth = brushWidth.value;
ctx.strokeStyle = brushColor.value;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
};
实现清除画布功能
添加清除按钮和对应方法:

<button @click="clearCanvas">清除</button>
const clearCanvas = () => {
const ctx = canvas.value.getContext('2d');
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
};
响应式调整画布尺寸
监听窗口变化调整画布大小:
onMounted(() => {
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
});
const resizeCanvas = () => {
canvas.value.width = canvas.value.offsetWidth;
canvas.value.height = canvas.value.offsetHeight;
};
保存画布为图片
添加保存功能:
<button @click="saveCanvas">保存</button>
const saveCanvas = () => {
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = canvas.value.toDataURL('image/png');
link.click();
};
触屏设备支持
添加触摸事件支持:
<canvas
ref="canvas"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="stopDrawing"
></canvas>
const handleTouchStart = (e) => {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousedown', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.value.dispatchEvent(mouseEvent);
};
const handleTouchMove = (e) => {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent('mousemove', {
clientX: touch.clientX,
clientY: touch.clientY
});
canvas.value.dispatchEvent(mouseEvent);
};
通过以上步骤可以实现一个功能完整的 Vue 画板应用,支持绘图、样式调整、清除和保存等功能。可根据需求进一步扩展,如添加撤销/重做、多种画笔类型或图层功能。






