canvas绘制环形进度条

效果如下

分析:将进度条分为两个部分,背景环与实体环,实体环包括中间文字,因此使用两个画布来实现。

代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
        <style>
            body {
                padding: 0;
                margin: 0;
            }
            .box {
                position: relative;
                width: 200;
                height: 200;
            }
            .bc,
            .pc {
                position: absolute;
                left: 0;
                top: 0;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
        <script>
            const bc = document.createElement('canvas')
            const pc = document.createElement('canvas')
            const box = document.querySelector('.box')
            const WIDTH = 200
            const HEIGHT = 200
            const LINE_WIDTH = 10
            bc.setAttribute('class', 'bg')
            pc.setAttribute('class', 'pc')
            bc.width = pc.width = WIDTH
            bc.height = pc.height = HEIGHT
            box.appendChild(bc)
            box.appendChild(pc)
            let bctx = bc.getContext('2d')
            let pctx = pc.getContext('2d')
            bctx.lineWidth = pctx.lineWidth = LINE_WIDTH
            bctx.strokeStyle = '#ebebeb'
            pctx.strokeStyle = 'red'
            pctx.lineCap = 'round'
            pctx.font = '50px Arial'
            pctx.textAlign = 'center'
            pctx.textBaseline = 'middle'
            pctx.fillStyle = 'gray'
            bctx.beginPath()
            bctx.arc(
                100,
                100,
                WIDTH / 2 - LINE_WIDTH / 2,
                0,
                Math.PI * 2,
                false
            )
            bctx.stroke()
            bctx.closePath()
            let angle = 0
            function draw() {
                pctx.clearRect(0, 0, 200, 200)
                pctx.beginPath()
                pctx.arc(
                    100,
                    100,
                    WIDTH / 2 - LINE_WIDTH / 2,
                    0,
                    (Math.PI * angle * 2) / 100,
                    false
                )
                pctx.stroke()
                pctx.closePath()
                pctx.beginPath()
                pctx.fillText(angle + '%', 100, 100)
                if (angle < 80) {
                    window.requestAnimationFrame(draw)
                }
                angle++
            }

            window.requestAnimationFrame(draw)
        </script>
    </body>
</html>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值