原生 js 画环形进度条

在这里插入图片描述


<!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>
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值