vue实现用户画图
Vue 实现用户画图功能
在 Vue 中实现用户画图功能,通常需要结合 HTML5 的 <canvas> 元素或第三方库。以下是几种实现方式:
使用原生 Canvas API
通过 Vue 直接操作 <canvas> 元素,监听鼠标事件实现绘图:

<template>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0
}
},
mounted() {
const canvas = this.$refs.canvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
},
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;
}
}
}
</script>
使用 Fabric.js 库
Fabric.js 是一个功能强大的 Canvas 库,简化了绘图操作:
npm install fabric
<template>
<canvas ref="canvas"></canvas>
</template>
<script>
import { fabric } from 'fabric';
export default {
mounted() {
this.canvas = new fabric.Canvas(this.$refs.canvas, {
isDrawingMode: true
});
}
}
</script>
使用 Konva.js 库
Konva.js 是另一个流行的 2D 绘图库,支持 Vue 集成:

npm install konva vue-konva
<template>
<v-stage ref="stage" :config="stageConfig">
<v-layer ref="layer">
<v-line v-for="(line, i) in lines" :key="i"
:config="line.config"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
/>
</v-layer>
</v-stage>
</template>
<script>
import { VueKonva } from 'vue-konva';
export default {
components: { VueKonva },
data() {
return {
stageConfig: { width: 800, height: 600 },
lines: [],
isDrawing: false
}
},
methods: {
handleMouseDown(e) {
this.isDrawing = true;
const pos = e.target.getStage().getPointerPosition();
this.lines.push({
config: {
points: [pos.x, pos.y],
stroke: '#df4b26',
strokeWidth: 5,
lineCap: 'round',
lineJoin: 'round'
}
});
},
handleMouseMove(e) {
if (!this.isDrawing) return;
const stage = e.target.getStage();
const point = stage.getPointerPosition();
const lastLine = this.lines[this.lines.length - 1];
lastLine.config.points = lastLine.config.points.concat([point.x, point.y]);
},
handleMouseUp() {
this.isDrawing = false;
}
}
}
</script>
实现橡皮擦功能
在原生 Canvas 实现中添加橡皮擦功能:
methods: {
setEraser() {
this.ctx.globalCompositeOperation = 'destination-out';
this.ctx.lineWidth = 20;
},
setPen() {
this.ctx.globalCompositeOperation = 'source-over';
this.ctx.lineWidth = 5;
}
}
保存绘图结果
将画布内容转换为图片并保存:
methods: {
saveImage() {
const dataURL = this.$refs.canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'drawing.png';
link.href = dataURL;
link.click();
}
}
以上方法提供了从基础到进阶的画图功能实现,可根据项目需求选择合适的方案。原生 Canvas API 适合轻量级需求,而 Fabric.js 和 Konva.js 更适合需要复杂交互和图形操作的场景。






