vue实现在线画图
Vue 实现在线画图的方法
使用 HTML5 Canvas 和 Vue 结合
HTML5 的 Canvas 元素非常适合用于在线画图。在 Vue 中可以通过指令或组件的方式集成 Canvas 功能。

<template>
<div>
<canvas
ref="canvas"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
@mouseleave="stopDrawing"
></canvas>
</div>
</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.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
},
methods: {
startDrawing(e) {
this.isDrawing = true;
this.ctx.beginPath();
this.ctx.moveTo(e.offsetX, e.offsetY);
},
draw(e) {
if (!this.isDrawing) return;
this.ctx.lineTo(e.offsetX, e.offsetY);
this.ctx.stroke();
},
stopDrawing() {
this.isDrawing = false;
}
}
}
</script>
使用第三方库 Fabric.js
Fabric.js 是一个功能强大的 Canvas 库,可以简化画图功能的实现。

<template>
<div>
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
import { fabric } from 'fabric';
export default {
data() {
return {
canvas: null
}
},
mounted() {
this.canvas = new fabric.Canvas(this.$refs.canvas, {
width: 800,
height: 600
});
this.canvas.on('mouse:down', (options) => {
const pointer = this.canvas.getPointer(options.e);
const circle = new fabric.Circle({
radius: 30,
fill: 'red',
left: pointer.x,
top: pointer.y
});
this.canvas.add(circle);
});
}
}
</script>
使用 SVG 和 Vue 结合
SVG 是另一种实现画图的方案,适合需要矢量图形的场景。
<template>
<div>
<svg
ref="svg"
@mousedown="startDrawing"
@mousemove="draw"
@mouseup="stopDrawing"
>
<path :d="pathData" stroke="black" fill="none" stroke-width="2" />
</svg>
</div>
</template>
<script>
export default {
data() {
return {
isDrawing: false,
pathData: '',
startX: 0,
startY: 0
}
},
methods: {
startDrawing(e) {
this.isDrawing = true;
const rect = this.$refs.svg.getBoundingClientRect();
this.startX = e.clientX - rect.left;
this.startY = e.clientY - rect.top;
this.pathData = `M${this.startX},${this.startY}`;
},
draw(e) {
if (!this.isDrawing) return;
const rect = this.$refs.svg.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.pathData += ` L${x},${y}`;
},
stopDrawing() {
this.isDrawing = false;
}
}
}
</script>
使用专门的 Vue 画图库
Vue Konva 是一个基于 Konva.js 的 Vue 封装库,适合复杂画图需求。
<template>
<v-stage ref="stage" :config="stageConfig">
<v-layer>
<v-circle
v-for="(circle, index) in circles"
:key="index"
:config="circle"
/>
</v-layer>
</v-stage>
</template>
<script>
import Vue from 'vue';
import VueKonva from 'vue-konva';
Vue.use(VueKonva);
export default {
data() {
return {
stageConfig: {
width: 800,
height: 600
},
circles: []
}
},
mounted() {
this.$refs.stage.getNode().on('click', (e) => {
this.circles.push({
x: e.evt.layerX,
y: e.evt.layerY,
radius: 30,
fill: 'red'
});
});
}
}
</script>
实现画图功能的关键点
- 选择合适的画图技术(Canvas/SVG/Konva)
- 处理鼠标事件(mousedown/mousemove/mouseup)
- 维护画图状态(是否正在画图)
- 实现画图逻辑(线条/形状/颜色)
- 考虑响应式设计(适应不同屏幕尺寸)
扩展功能建议
- 添加颜色选择器
- 实现线条粗细调整
- 添加撤销/重做功能
- 实现保存图片功能
- 添加多种形状工具(矩形/圆形/自由线条)
以上方法可以根据具体需求选择适合的方案,从简单到复杂逐步实现画图功能。






