js实现环图
使用 Canvas 绘制环图
Canvas 是 HTML5 提供的绘图 API,适合动态生成图形。以下代码示例展示如何绘制一个基础环图:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 100;
const lineWidth = 30;
function drawRing(percentage, color) {
const startAngle = -Math.PI / 2;
const endAngle = startAngle + (percentage * Math.PI * 2);
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.strokeStyle = '#eee';
ctx.lineWidth = lineWidth;
ctx.stroke();
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.stroke();
}
drawRing(0.75, '#4285F4'); // 75% 完成度
使用 SVG 创建环图
SVG 是矢量图形标准,适合需要缩放且保持清晰度的场景:
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="80"
stroke="#eee" stroke-width="20" fill="none"/>
<circle cx="100" cy="100" r="80"
stroke="#4285F4" stroke-width="20"
stroke-dasharray="502.65"
stroke-dashoffset="${502.65 * (1 - 0.75)}"
fill="none" transform="rotate(-90 100 100)"/>
</svg>
计算公式:
- 周长 = 2 π r → 2 3.1416 80 ≈ 502.65
- dashoffset = 周长 * (1 - 百分比)
使用 Chart.js 库
Chart.js 提供现成的环形图(doughnut chart)组件:
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: [75, 25],
backgroundColor: ['#4285F4', '#eee'],
borderWidth: 0
}]
},
options: {
cutout: '70%'
}
});
使用 CSS 实现简易环图
纯 CSS 方案适合简单场景,通过 conic-gradient 实现:
<div class="ring" style="--percent:75;--color:#4285F4;"></div>
<style>
.ring {
width: 200px;
height: 200px;
border-radius: 50%;
background: conic-gradient(
var(--color) 0% calc(var(--percent) * 1%),
#eee calc(var(--percent) * 1%) 100%
);
position: relative;
}
.ring::after {
content: '';
position: absolute;
width: 80%;
height: 80%;
background: white;
border-radius: 50%;
top: 10%;
left: 10%;
}
</style>
添加动画效果
为 SVG 环图添加 CSS 动画:
circle[stroke="#4285F4"] {
animation: ringFill 1.5s ease-out forwards;
}
@keyframes ringFill {
from { stroke-dashoffset: 502.65; }
to { stroke-dashoffset: 125.66; } /* 对应 75% */
}
响应式设计技巧
确保环图适应不同屏幕尺寸:

function resizeCanvas() {
const container = document.querySelector('.chart-container');
canvas.width = container.clientWidth;
canvas.height = container.clientWidth; // 保持正方形
drawRing(); // 重绘
}
window.addEventListener('resize', resizeCanvas);






