js实现圆环
实现圆环的几种方法
使用CSS和JavaScript可以创建圆环效果,以下是几种常见的实现方式:
使用CSS border-radius和border
通过设置元素的border-radius为50%创建圆形,再通过border属性控制圆环粗细:

<div class="circle"></div>
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
border: 10px solid #3498db;
background-color: transparent;
}
使用Canvas绘制圆环
通过Canvas API可以更灵活地绘制圆环:
<canvas id="myCanvas" width="200" height="200"></canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 20;
ctx.strokeStyle = '#e74c3c';
ctx.stroke();
使用SVG创建圆环
SVG是矢量图形,适合创建圆环:

<svg width="200" height="200">
<circle cx="100" cy="100" r="80"
stroke="#2ecc71" stroke-width="20" fill="none"/>
</svg>
动态进度圆环
结合Canvas和JavaScript可以实现动态进度圆环:
function drawProgressRing(percent) {
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 = 15;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = '#ecf0f1';
ctx.stroke();
// 绘制进度圆环
const endAngle = (percent / 100) * 2 * Math.PI - Math.PI/2;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI/2, endAngle);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = '#3498db';
ctx.stroke();
}
// 使用示例
drawProgressRing(75); // 绘制75%的进度圆环
CSS动画圆环
使用CSS动画可以创建旋转的圆环效果:
.spinner {
width: 100px;
height: 100px;
border: 10px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-left-color: #3498db;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
以上方法可以根据具体需求选择使用,CSS方法简单高效,Canvas和SVG提供更多自定义选项,适合复杂交互场景。






