美文网首页
canvas 进度圆环

canvas 进度圆环

作者: _____西班木有蛀牙 | 来源:发表于2020-06-17 23:29 被阅读0次
image.png
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      background-color: #131A2B;
    }

    #c1 {
      display: block;
      margin: 10px auto;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <canvas width="110" height="110" id="c1"></canvas>
  <script>
    var c1 = document.querySelector('#c1')
    var ctx = c1.getContext('2d')

    ctx.translate(c1.width / 2, c1.height / 2)
    ctx.arc(0, 0, 45, 0, Math.PI * 2)
    ctx.lineWidth = 15
    ctx.strokeStyle = '#172D49'
    ctx.stroke()
    ctx.beginPath()

    ctx.arc(0, 0, 32, 0, Math.PI * 2)
    ctx.lineWidth = 2
    var lingrad = ctx.createLinearGradient(0, -15, 0, 28);
    lingrad.addColorStop(0, 'rgba(64,162,254,1)');
    lingrad.addColorStop(0.3, 'rgba(64,162,254,0.25)');
    lingrad.addColorStop(1, 'rgba(64,162,254,0)');
    ctx.strokeStyle = lingrad
    ctx.stroke()
    ctx.beginPath()


    ctx.font = '20px Microsoft YaHei'
    ctx.fillStyle = '#fff'
    ctx.fillText('0%', -ctx.measureText('0%').width / 2, 5)

    function process(percentage) {
      console.log(percentage)
      let current = 0;
      // 圆环背景
      ctx.beginPath()
      ctx.arc(0, 0, 45, 0, Math.PI * 2)
      ctx.lineWidth = 15
      ctx.strokeStyle = '#172D49'
      ctx.stroke()
      ctx.beginPath()


      const pro = () => {
        ctx.clearRect(-60, -60, 120, 120)

        ctx.arc(0, 0, 32, 0, Math.PI * 2)
        ctx.lineWidth = 2
        var lingrad = ctx.createLinearGradient(0, -15, 0, 28);
        lingrad.addColorStop(0, 'rgba(64,162,254,1)');
        lingrad.addColorStop(0.3, 'rgba(64,162,254,0.25)');
        lingrad.addColorStop(1, 'rgba(64,162,254,0)');
        ctx.strokeStyle = lingrad
        ctx.stroke()
        ctx.beginPath()

        // 圆环背景
        ctx.beginPath()
        ctx.arc(0, 0, 45, 0, Math.PI * 2)
        ctx.lineWidth = 15
        ctx.strokeStyle = '#172D49'
        ctx.stroke()
        ctx.beginPath()

        if (current + 1 < percentage) {
          current += 1
        } else {
          current = percentage
        }
        ctx.beginPath()
        ctx.arc(0, 0, 45, -Math.PI * 2 / 4, Math.PI * 2 / 100 * (current + 1 - 25))
        ctx.strokeStyle = 'rgba(64,162,254,1)'
        ctx.stroke()
        ctx.beginPath()
        ctx.font = '20px Microsoft YaHei'
        ctx.fillStyle = '#fff'
        const p = current + '%'
        const pl = ctx.measureText(p)
        console.log(p, pl.width)
        ctx.fillText(p, -pl.width / 2, 5)
        if (current >= percentage) {
          return
        }
        requestAnimationFrame(() => {
          pro(percentage)
        }, 100)
      }
      pro(percentage < 0 ? 0 : percentage)
    }

  </script>
</body>

</html>

相关文章

网友评论

      本文标题:canvas 进度圆环

      本文链接:https://www.haomeiwen.com/subject/rbzexktx.html