js实现圆环
使用 SVG 实现圆环
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,适合绘制圆环。以下是一个简单的 SVG 圆环实现:
<svg width="200" height="200">
<circle cx="100" cy="100" r="80" fill="none" stroke="#ccc" stroke-width="10"/>
<circle cx="100" cy="100" r="80" fill="none" stroke="#f00" stroke-width="10" stroke-dasharray="251.2" stroke-dashoffset="125.6"/>
</svg>
cx 和 cy 定义圆心坐标,r 是半径。stroke-dasharray 控制虚线样式,stroke-dashoffset 控制起始偏移量。

使用 Canvas 绘制圆环
Canvas 提供了更灵活的绘制方式,适合动态圆环:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 80;
const lineWidth = 10;
// 背景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.strokeStyle = '#ccc';
ctx.lineWidth = lineWidth;
ctx.stroke();
// 前景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI/2, Math.PI);
ctx.strokeStyle = '#f00';
ctx.lineWidth = lineWidth;
ctx.stroke();
使用 CSS 实现圆环
纯 CSS 方案利用 border 和 border-radius 属性:

<div class="ring-container">
<div class="ring-background"></div>
<div class="ring-foreground"></div>
</div>
<style>
.ring-container {
position: relative;
width: 200px;
height: 200px;
}
.ring-background {
position: absolute;
width: 100%;
height: 100%;
border: 10px solid #ccc;
border-radius: 50%;
box-sizing: border-box;
}
.ring-foreground {
position: absolute;
width: 100%;
height: 100%;
border: 10px solid transparent;
border-top-color: #f00;
border-radius: 50%;
box-sizing: border-box;
transform: rotate(135deg);
}
</style>
动态进度圆环(Canvas)
实现一个可交互的进度圆环:
function drawProgressRing(progress) {
const canvas = document.getElementById('progressCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 80;
const lineWidth = 10;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 背景
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, -Math.PI/2, -Math.PI/2 + Math.PI*2*progress/100);
ctx.strokeStyle = '#4CAF50';
ctx.lineWidth = lineWidth;
ctx.stroke();
// 文字
ctx.font = '24px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(`${progress}%`, centerX, centerY);
}
// 使用示例
drawProgressRing(75); // 绘制75%的进度
动画效果实现
为圆环添加动画效果:
function animateRing(targetProgress, duration = 1000) {
let startTime = null;
let currentProgress = 0;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
currentProgress = progress * targetProgress;
drawProgressRing(currentProgress);
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 启动动画
animateRing(80); // 动画到80%
这些方法提供了从简单到复杂的圆环实现方案,可根据具体需求选择最适合的方式。SVG 适合静态展示,Canvas 适合动态和交互场景,CSS 方案则无需 JavaScript 即可实现基本效果。






