SVG实现环形进度条

485 阅读1分钟

image.png

介绍

SVG 是可缩放形矢量图形,也就是说它可以在图形放大的情况下不会失真。

SVG 内部有很多独有的标签,利用这些标签可以轻松完成一些图像开发和一些丰富的交互操作

本篇文章利用SVG实现一个环形进度条的效果

代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .text {
      text-anchor: middle;
      /* 横向对齐方式 默认是根据x y 的start对齐,midele为居中 */
      dominant-baseline: middle;
      /* 纵向对齐方式 */
    }
  </style>
</head>

<body>
  <svg height="700" width="700">
    <circle cx="350" cy="350" r="300" fill="none" stroke="grey" stroke-width="40" stroke-linecap="round">

    </circle>
    <circle class="progress" cx="350" cy="350" r="300" fill="none" stroke="red" stroke-width="40" stroke-linecap="round"
      stroke-dasharray="1,2000" transform="rotate(-90, 350,350)">

    </circle>
    <text font-size="200" x="350" y="350" fill="red" class="text">0%</text>
  </svg>
</body>

</html>
<script>
  const [progress] = document.getElementsByClassName('progress');
  const [text] = document.getElementsByClassName('text');

  function rotateCircle(proportion) {
    // 获取圆的面积
    const circleLength = Math.floor(2 * Math.PI * progress.getAttribute('r'));
    // 分为100份  一份的长度
    const oneLength = circleLength / 100;
    // 求出 当前的份数的长度
    const value = proportion * oneLength;
    // 设置随机颜色
    const green = parseInt(proportion / 100 * 200)
    const blue = parseInt(proportion / 100 * 255)
    
    progress.setAttribute('stroke-dasharray', `${value},2000`)
    progress.setAttribute('stroke', `rgb(${255},${green},${blue})`)
    text.setAttribute('fill', `rgb(${255},${green},${blue})`)
    text.innerHTML = `${proportion}%`
  }
  let num = 0
  setInterval(() => {
    if (num > 100) { // 最大比例0
      num = 0
    }

    rotateCircle(++num)
  }, 30)
</script>

分析

  • html 可以看到代码里用到了SVG里的circle标签和text标签, 利用circle标签完成画圆,text标签表示文本, 其中两个圆,一个圆表示底图的圆,也就是背景的灰色圆边,另一个圆表示当前进度,利用stroke-dasharray属性用来表示当前的进度情况

  • js

js 中就是获取到圆的边长并且分为 100 份,求出每份的长度赋值给stroke-dasharray属性来实现进度条的百分比