vue实现动态弧线
Vue 实现动态弧线
在 Vue 中实现动态弧线可以通过多种方式,以下是两种常见的方法:使用 SVG 和 Canvas。
使用 SVG 绘制动态弧线
SVG 提供了一种简单的方式来绘制弧线,并且可以通过 Vue 动态更新属性。
<template>
<svg width="200" height="200">
<path
:d="arcPath"
fill="none"
stroke="blue"
stroke-width="2"
/>
</svg>
</template>
<script>
export default {
data() {
return {
startAngle: 0,
endAngle: 180
};
},
computed: {
arcPath() {
const radius = 80;
const centerX = 100;
const centerY = 100;
const startRad = (this.startAngle * Math.PI) / 180;
const endRad = (this.endAngle * Math.PI) / 180;
const x1 = centerX + radius * Math.cos(startRad);
const y1 = centerY + radius * Math.sin(startRad);
const x2 = centerX + radius * Math.cos(endRad);
const y2 = centerY + radius * Math.sin(endRad);
const largeArcFlag = this.endAngle - this.startAngle <= 180 ? 0 : 1;
return `M ${centerX} ${centerY} L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2} Z`;
}
},
mounted() {
setInterval(() => {
this.startAngle = (this.startAngle + 1) % 360;
this.endAngle = (this.endAngle + 2) % 360;
}, 50);
}
};
</script>
使用 Canvas 绘制动态弧线
Canvas 提供了更灵活的绘图能力,适合复杂的动态效果。
<template>
<canvas ref="canvas" width="200" height="200"></canvas>
</template>
<script>
export default {
data() {
return {
angle: 0
};
},
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(100, 100, 80, 0, (this.angle * Math.PI) / 180);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
this.angle = (this.angle + 1) % 360;
requestAnimationFrame(animate);
};
animate();
}
};
</script>
使用第三方库(如 D3.js)
如果需要更复杂的弧线动画,可以使用 D3.js 这样的库。

<template>
<svg ref="svg" width="200" height="200"></svg>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
const svg = d3.select(this.$refs.svg);
const arcGenerator = d3.arc()
.innerRadius(0)
.outerRadius(80)
.startAngle(0)
.endAngle(Math.PI / 2);
svg.append('path')
.attr('d', arcGenerator())
.attr('fill', 'none')
.attr('stroke', 'blue')
.attr('stroke-width', 2);
}
};
</script>
以上方法可以根据具体需求选择,SVG 适合简单的动态效果,Canvas 适合高性能需求,D3.js 适合复杂的数据可视化场景。






