vue消除笔实现
Vue 消除笔实现
在 Vue 中实现消除笔功能通常涉及 Canvas 绘图和交互处理。以下是实现步骤:
初始化 Canvas 和 Vue 组件
在 Vue 组件中创建 Canvas 元素并设置基础属性:
<template>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
</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);
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeCanvas);
}
}
</script>
实现绘图逻辑
添加绘图方法,使用 globalCompositeOperation 控制擦除效果:
methods: {
resizeCanvas() {
this.canvas.width = this.canvas.offsetWidth;
this.canvas.height = this.canvas.offsetHeight;
},
startDrawing(e) {
this.isDrawing = true;
this.draw(e);
},
draw(e) {
if (!this.isDrawing) return;
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.ctx.globalCompositeOperation = 'destination-out';
this.ctx.beginPath();
this.ctx.arc(x, y, 10, 0, Math.PI * 2);
this.ctx.fill();
},
stopDrawing() {
this.isDrawing = false;
}
}
添加背景图像
擦除效果需要可见的背景:
loadImage() {
const img = new Image();
img.onload = () => {
this.ctx.drawImage(img, 0, 0, this.canvas.width, this.canvas.height);
this.ctx.globalCompositeOperation = 'source-over';
};
img.src = '/path/to/image.jpg';
}
优化性能
使用 requestAnimationFrame 优化绘制性能:
draw(e) {
if (!this.isDrawing) return;
window.requestAnimationFrame(() => {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.ctx.globalCompositeOperation = 'destination-out';
this.ctx.beginPath();
this.ctx.arc(x, y, 10, 0, Math.PI * 2);
this.ctx.fill();
});
}
移动端支持
添加触摸事件支持:
<canvas
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
handleTouch(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent(
e.type === 'touchstart' ? 'mousedown' :
e.type === 'touchmove' ? 'mousemove' : 'mouseup',
{
clientX: touch.clientX,
clientY: touch.clientY
}
);
this.canvas.dispatchEvent(mouseEvent);
}
注意事项
- 擦除效果依赖
globalCompositeOperation设置为'destination-out' - 需要预先加载背景图像才能看到擦除效果
- 擦除笔大小通过
arc方法的半径参数调整 - 移动端需要阻止默认触摸行为防止页面滚动
完整实现需要考虑更多细节如撤销功能、不同形状的擦除笔等,但以上代码提供了核心功能实现。







