首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

[代码]一个倒计时5S的圆环案例

鸟云Lv.1普通用户
2024-08-30 23:57:46
0
148

canvas实现

<!DOCTYPE html>
<html>
    <body>
        <canvas id="countdownCanvas" width="200" height="200"></canvas>

        <script>
            const canvas = document.getElementById('countdownCanvas');
            const ctx = canvas.getContext('2d');
            const centerX = canvas.width / 2;
            const centerY = canvas.height / 2;
            const radius = 70;

            let count = 5; // 倒计时5秒
            let angle = 0; // 起始角度
            let timer; // 计时器

            function drawCircle(count) {
                ctx.beginPath();
                var endAngle = (Math.PI * 2) / 5 * count; // 每次调用增加约2度
                ctx.arc(centerX, centerY, radius, 0, endAngle);
                var g = ctx.createLinearGradient(-0.5 * Math.PI, count, 180, 0); //创建渐变对象  渐变开始点和渐变结束点
                g.addColorStop(0, '#17d1ff'); //添加颜色点
                g.addColorStop(1, '#209cff'); //添加颜色点
                ctx.strokeStyle = g; //使用渐变对象作为圆环的颜色
                ctx.lineWidth = 10;
                ctx.stroke();
            }

            function drawCountdown() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                countdownTimer = setInterval(function() {
                    if (count > 0) {
                        count--;
                        console.log("倒计时:" + count)
                        drawCircle(5 - count);
                    } else {
                        clearInterval(countdownTimer);
                    }
                }, 1000);

            }
            drawCountdown()// 开始倒计时
        </script>

    </body>
</html>
鸟云
鸟云

52 天前

签名 :   148       0
评论
站长交流