canvas实现百分比&扇形效果

本文介绍如何使用HTML5的Canvas元素绘制一个动态更新的百分比环形图,通过JavaScript控制动画效果,实现从0%到100%的渐进填充过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

<!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>
</head>

<body>
    <div class="wrap">
        <canvas width="400" height="400" id="vas" style="background: gray;"></canvas>
    </div>
    <script>
        var can = document.getElementById('vas');
        var ctx = can.getContext('2d');
        rad = Math.PI * 2 / 100;//将360度分成100份
        // 画圆
        function circle() {
            ctx.beginPath();
            ctx.arc(200, 200, 100, 0, Math.PI * 2, false);
            ctx.closePath();
            ctx.fillStyle = 'green';
            ctx.fill();
        }

        // 百分比
        function text(n) {
            ctx.save();
            // ctx.strokeStyle = "orangered";
            ctx.font = "40px Arial";
            ctx.fillStyle = "#fff";
            ctx.fillText(n + "%", 200 - 35, 200 + 10);
            // ctx.fill();
            ctx.restore();
        }
        // 画圆弧
        var val = 1;
        ctx.beginPath();
        ctx.moveTo(200, 200);
        ctx.arc(200, 200, 100, 0, rad, false);
        ctx.closePath();
        ctx.fillStyle = 'red';
        ctx.fill();
        (function draw() {
            val++;
            circle()
            ctx.beginPath();
            ctx.moveTo(200, 200);
            ctx.arc(200, 200, 100, 0, val * rad, false);
            ctx.closePath();
            ctx.fillStyle = 'red';
            ctx.fill();
            // console.log(val);
            text(val);
            if (val >= 100) {
                val = 0;
            }
            requestAnimationFrame(draw);

        })();

    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

本地是好的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值