js实现圆环
使用 SVG 实现圆环
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,适合绘制圆环等图形。

<svg width="200" height="200">
<circle cx="100" cy="100" r="80" fill="none" stroke="#3498db" stroke-width="10" />
</svg>
cx和cy定义圆心坐标r定义半径fill设置填充颜色(none 表示无填充)stroke设置边框颜色stroke-width设置边框宽度
使用 Canvas 实现圆环
Canvas 提供更灵活的绘制方式,适合需要动态效果的场景。

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 80, 0, 2 * Math.PI);
ctx.strokeStyle = '#e74c3c';
ctx.lineWidth = 10;
ctx.stroke();
arc()方法绘制圆弧- 参数依次为:圆心 x, 圆心 y, 半径, 起始角度, 结束角度
strokeStyle设置描边颜色lineWidth设置线宽
使用 CSS 实现圆环
纯 CSS 方案适合简单的静态圆环需求。
<div class="ring"></div>
<style>
.ring {
width: 160px;
height: 160px;
border-radius: 50%;
border: 10px solid #2ecc71;
background: transparent;
}
</style>
border-radius: 50%创建圆形- 透明背景配合边框形成圆环效果
- 调整
border-width控制圆环粗细
动态进度圆环实现
结合 Canvas 和 JavaScript 可以创建动态进度圆环。
function drawProgressRing(percent) {
const canvas = document.getElementById('progressCanvas');
const ctx = canvas.getContext('2d');
const x = canvas.width / 2;
const y = canvas.height / 2;
const radius = 70;
const lineWidth = 15;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景圆环
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#ecf0f1';
ctx.lineWidth = lineWidth;
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(x, y, radius, -0.5 * Math.PI, (percent / 100) * 2 * Math.PI - 0.5 * Math.PI);
ctx.strokeStyle = '#f39c12';
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.stroke();
// 绘制百分比文本
ctx.fillStyle = '#34495e';
ctx.font = '24px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(`${percent}%`, x, y);
}
// 示例:绘制75%进度
drawProgressRing(75);
- 使用
clearRect()清除之前绘制的内容 - 通过计算角度实现进度效果
lineCap设置线段末端样式- 添加文本显示当前进度百分比






