要在网页中使用 JavaScript 和 CSS 绘制一个圆环进度条,可以利用 HTML5 的 <canvas>
元素或者纯 CSS 结合 SVG 来实现。下面将介绍一种使用纯 CSS 和 SVG 实现圆环进度条的方法,并附带相关代码示例。
圆环进度条通常由两个同心圆组成,外层为进度条的背景,内层根据进度动态变化,显示当前的完成度。通过调整内层圆的旋转角度或宽度,可以实现进度的可视化效果。
以下是使用纯 CSS 和 SVG 实现圆环进度条的示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>圆环进度条示例</title>
<style>
.progress-container {
position: relative;
width: 150px;
height: 150px;
}
.progress-container svg {
transform: rotate(-90deg);
width: 100%;
height: 100%;
}
.progress-container circle {
fill: none;
stroke-width: 10;
stroke-linecap: round;
}
.progress-container .background {
stroke: #eee;
}
.progress-container .progress {
stroke: #007bff;
stroke-dasharray: 471; /* 2 * π * r (r=50) */
stroke-dashoffset: 471;
animation: draw 3s linear forwards;
}
@keyframes draw {
to {
stroke-dashoffset: 0;
}
}
</style>
</head>
<body>
<div class="progress-container">
<svg viewBox="0 0 100 100">
<circle class="background" cx="50" cy="50" r="50"></circle>
<circle class="progress" cx="50" cy="50" r="50"></circle>
</svg>
</div>
</body>
</html>
.progress-container
。<circle>
元素,分别代表背景圆环和进度圆环。stroke-dasharray
和 stroke-dashoffset
控制进度显示。draw
,使进度圆环逐渐填充。.progress
类中的 stroke
属性即可更改进度条颜色。.progress-container
的 width
和 height
,以及 SVG 中圆的 r
属性。animation: draw 3s linear forwards;
中的 3s
来调整动画时长。stroke-dasharray
的值等于圆的周长(2 * π * r
)。viewBox
是否正确设置,确保圆环在可视范围内。will-change: transform;
或 transform: translateZ(0);
来优化动画性能。通过结合 CSS 和 SVG,可以轻松创建美观且高效的圆环进度条。这种方法不仅实现简单,而且具有良好的可定制性和响应式特性,适用于多种网页设计需求。
领取专属 10元无门槛券
手把手带您无忧上云