<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="progress-container">
<svg class="progress-svg" viewBox="0 0 100 100">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#007bff;stop-opacity:1" />
<stop offset="100%" style="stop-color:#ff7f00;stop-opacity:1" />
</linearGradient>
</defs>
<circle class="progress-bg" cx="50" cy="50" r="45"></circle>
<circle class="progress" cx="50" cy="50" r="45" transform="rotate(90 50 50)"></circle>
</svg>
<span class="progress-text">0%</span>
</div>
<style>
.progress-container {
position: relative;
width: 100px;
height: 100px;
}
.progress-svg {
width: 100%;
height: 100%;
}
.progress-bg {
fill: none;
stroke: #ddd;
stroke-width: 4;
}
.progress {
fill: none;
stroke: url(#gradient);
/* 使用线性渐变填充 */
stroke-width: 4;
stroke-dasharray: 0 283;
/* 圆形的周长是 2 * Math.PI * r,这里设置为2 * 45 * Math.PI = 283 */
stroke-dashoffset: 0;
/* 进度条的起始位置 */
transition: stroke-dasharray 0.3s;
}
.progress-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 16px;
color: #333;
}
</style>
<script>
function setProgress(percent) {
const circle = document.querySelector('.progress');
const radius = circle.r.baseVal.value;
const circumference = 2 * Math.PI * radius;
const offset = circumference - percent / 100 * circumference;
circle.style.strokeDasharray = `${circumference} ${circumference}`;
circle.style.strokeDashoffset = offset;
const text = document.querySelector('.progress-text');
text.textContent = `${percent}%`;
}
// 示例:设置进度为50%
setProgress(50);
</script>
</body>
</html>
原生 js 画环形进度条
最新推荐文章于 2024-05-31 10:29:13 发布