vue 实现平面
Vue 实现平面图形绘制的方法
在Vue中实现平面图形绘制可以通过多种方式完成,常见的有使用Canvas API、SVG或第三方库如D3.js、Three.js(2D模式)等。以下是几种具体实现方法:
使用Canvas API绘制
通过Vue的<canvas>元素结合JavaScript的Canvas API,可以直接绘制平面图形。需要在Vue组件的mounted生命周期钩子中操作Canvas上下文。

<template>
<canvas ref="canvas" width="400" height="400"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
}
};
</script>
使用SVG绘制
SVG是矢量图形标准,可以直接嵌入Vue模板中。SVG图形支持动态绑定和响应式更新。

<template>
<svg width="400" height="400">
<!-- 矩形 -->
<rect x="50" y="50" width="100" height="100" fill="blue" />
<!-- 圆形 -->
<circle cx="200" cy="200" r="50" fill="red" />
</svg>
</template>
使用第三方库(D3.js)
D3.js适合数据驱动的动态图形。以下是一个简单的D3.js在Vue中绘制柱状图的示例:
<template>
<div ref="d3Container"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
const data = [10, 20, 30, 40, 50];
const svg = d3.select(this.$refs.d3Container)
.append('svg')
.attr('width', 400)
.attr('height', 200);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', (d, i) => i * 60)
.attr('y', d => 100 - d)
.attr('width', 50)
.attr('height', d => d)
.attr('fill', 'green');
}
};
</script>
使用Three.js的2D模式
Three.js虽然是3D库,但可通过正交相机实现2D效果:
<template>
<div ref="threeContainer"></div>
</template>
<script>
import * as THREE from 'three';
export default {
mounted() {
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(0, 400, 400, 0, 1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 400);
this.$refs.threeContainer.appendChild(renderer.domElement);
const geometry = new THREE.PlaneGeometry(100, 100);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const plane = new THREE.Mesh(geometry, material);
plane.position.set(200, 200, 0);
scene.add(plane);
renderer.render(scene, camera);
}
};
</script>
选择建议
- 简单静态图形:优先使用SVG,语法直观且易于维护。
- 动态或复杂图形:Canvas API或D3.js更适合数据绑定和动画。
- 游戏或高性能需求:考虑Canvas或WebGL库(如Three.js的2D模式)。






