vue 实现平面
Vue 实现平面图形绘制
Vue 结合 HTML5 的 <canvas> 或 SVG 可以实现平面图形的绘制。以下是两种常见方法的实现方式:
使用 Canvas 绘制平面图形
Canvas 提供基础的 2D 绘图 API,适合动态图形或复杂绘图需求。
<template>
<canvas ref="canvas" width="400" height="400"></canvas>
</template>
<script>
export default {
mounted() {
this.drawCanvas();
},
methods: {
drawCanvas() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(250, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
}
}
};
</script>
使用 SVG 绘制平面图形
SVG 是矢量图形标准,适合静态或需要交互的图形。
<template>
<svg width="400" height="400">
<!-- 矩形 -->
<rect x="50" y="50" width="100" height="100" fill="blue" />
<!-- 圆形 -->
<circle cx="250" cy="100" r="50" fill="red" />
</svg>
</template>
使用第三方库(如 D3.js 或 Konva)
对于复杂场景,可以集成专业图形库:

<template>
<div ref="container"></div>
</template>
<script>
import Konva from 'konva';
export default {
mounted() {
const stage = new Konva.Stage({
container: this.$refs.container,
width: 400,
height: 400,
});
const layer = new Konva.Layer();
const rect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 100,
fill: 'blue',
});
layer.add(rect);
stage.add(layer);
}
};
</script>
关键注意事项
- 响应式更新:Vue 数据变化时需手动触发图形重绘(Canvas)或使用计算属性(SVG)
- 性能优化:复杂图形建议使用离屏 Canvas 或 WebGL
- 事件处理:SVG 原生支持 DOM 事件,Canvas 需手动实现坐标检测
以上方法可根据项目需求选择,简单图形推荐 SVG,游戏或数据可视化优先考虑 Canvas 或专业库。






