当前位置:   article > 正文

canvas画一个环形进度条_canvas环形进度条

canvas环形进度条

» 介绍

用canvas画一个环形进度条,效果如下:
请添加图片描述

预览地址:https://ux93p.csb.app/


» 代码如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>canvas环形进度条</title>
    <style>
      body {
        margin: 30px 0;
        text-align: center;
      }

      #canvas {
        background: #f6f6f6;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="300" height="300">您的浏览器不支持 HTML5 canvas 标签。</canvas>
    <script>
      let c = document.getElementById('canvas')
      let ctx = c.getContext('2d')
      let precent = 80,
        num = 0

      function options(color, x, y, radius, start, end, order) {
        ctx.save()
        ctx.beginPath()
        ctx.lineCap = 'round'
        ctx.lineWidth = 8
        ctx.strokeStyle = color
        ctx.arc(x, y, radius, start, end, order) //x坐标,y坐标,半径,起始角,结束角,顺时针/逆时针
        ctx.stroke()
        ctx.closePath()
        ctx.restore()
      }

      //绘制文字
      function drawText(num) {
        ctx.save()
        ctx.fillStyle = '#2ba0fb'

        ctx.font = '40px Helvetica'
        ctx.textAlign = 'center'
        ctx.fillText(num + '%', 150, 160)
        ctx.restore()
      }

      //动画
      (function draw() {
        num += 1
        if (num < precent) window.requestAnimationFrame(draw)
        else num = precent
        ctx.clearRect(0, 0, 300, 300)
        options('#e5f1fa', 150, 150, 100, 0, 2 * Math.PI) //绘制轨道
        options('#2ba0fb', 150, 150, 100, -Math.PI / 2, -Math.PI / 2 + ((2 * num) / 100) * Math.PI) //绘制进度环
        drawText(num)
      })()
    </script>
  </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

» 重点

根据进度来计算起始角度和终止角度:

ctx.arc(150, 150, 100, -Math.PI / 2, -Math.PI / 2 + 2 * num / 100 * Math.PI)


相关推荐:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/254302
推荐阅读
相关标签