vue实现页面手写
Vue 实现页面手写功能
使用 Canvas 实现手写板
在 Vue 中可以通过 Canvas 实现手写功能。创建一个组件,包含 Canvas 元素,监听鼠标或触摸事件来绘制路径。
<template>
<div>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
<button @click="clearCanvas">清除</button>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
};
},
mounted() {
this.setupCanvas();
},
methods: {
setupCanvas() {
const canvas = this.$refs.canvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
this.ctx.strokeStyle = '#000';
this.ctx.lineWidth = 2;
this.ctx.lineCap = 'round';
},
startDrawing(e) {
this.isDrawing = true;
const pos = this.getPosition(e);
this.lastX = pos.x;
this.lastY = pos.y;
},
draw(e) {
if (!this.isDrawing) return;
const pos = this.getPosition(e);
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(pos.x, pos.y);
this.ctx.stroke();
this.lastX = pos.x;
this.lastY = pos.y;
},
stopDrawing() {
this.isDrawing = false;
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
},
getPosition(e) {
const canvas = this.$refs.canvas;
const rect = canvas.getBoundingClientRect();
return {
x: (e.clientX || e.touches[0].clientX) - rect.left,
y: (e.clientY || e.touches[0].clientY) - rect.top
};
}
}
};
</script>
<style>
canvas {
border: 1px solid #000;
background-color: #fff;
cursor: crosshair;
}
</style>
保存手写内容为图片
可以将 Canvas 绘制的内容转换为图片并保存或上传。
methods: {
saveAsImage() {
const canvas = this.$refs.canvas;
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = image;
link.download = 'signature.png';
link.click();
}
}
使用第三方库优化体验
对于更复杂的手写需求,可以使用第三方库如 Signature Pad:

安装:
npm install signature_pad
使用:

<template>
<div>
<canvas ref="canvas"></canvas>
<button @click="clear">清除</button>
<button @click="save">保存</button>
</div>
</template>
<script>
import SignaturePad from 'signature_pad';
export default {
mounted() {
this.signaturePad = new SignaturePad(this.$refs.canvas);
},
methods: {
clear() {
this.signaturePad.clear();
},
save() {
const data = this.signaturePad.toDataURL('image/png');
console.log(data);
}
}
};
</script>
响应式处理
确保 Canvas 在窗口大小变化时保持正确尺寸:
mounted() {
this.setupCanvas();
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.setupCanvas();
}
}
移动端适配
对于移动设备,需要额外处理触摸事件和防止页面滚动:
methods: {
preventScrolling(e) {
e.preventDefault();
}
},
mounted() {
this.$refs.canvas.addEventListener('touchmove', this.preventScrolling, { passive: false });
}
以上方法提供了在 Vue 中实现手写功能的基本方案,可以根据实际需求进行调整和扩展。






