使用js和canvas写一个时钟

使用js和canvas写一个时钟
在这里插入图片描述

<!DOCTYPE html>`
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id='canvas' width='600' height='600' style="border: 1px solid red;"></canvas>
    <script>
        /** @type {HTMLCanvasElement} */
        let canvas = document.querySelector("#canvas");
        let ctx = canvas.getContext("2d");
        let deg = Math.PI / 180;

        let HourR = 100;
        let MinutesR = 135;
        let SecondsR = 170;
        setInterval(function () {

            canvas.width = canvas.width;
            ctx.arc(300, 300, 200, 0, Math.PI * 2)
            ctx.fillStyle = 'rgba(10,100,30,0.2)'
            ctx.strokeStyle = 'red'
            //获取当前时间
            let dt = new Date()
            let Hour = dt.getHours()
            let Minutes = dt.getMinutes()
            let Seconds = dt.getSeconds()
            //时钟
            ctx.moveTo(300, 300);
            let xx = HourR * (Math.sin(Hour * 30 * deg))
            let yy = HourR * (Math.cos(Hour * 30 * deg))
            ctx.lineTo((300 + xx), (300 - yy))
            //分钟和秒钟
            function move(time, R) {
                ctx.moveTo(300, 300);
                xx = R * (Math.sin(time * 6 * deg))
                yy = R * (Math.cos(time * 6 * deg))
                ctx.lineTo((300 + xx), (300 - yy))
            }
            //小时指针
            for (let m = 0; m < 12; m++) {
                let xx = 190 * (Math.sin(m * 30 * deg))
                let yy = 190 * (Math.cos(m * 30 * deg))
                let xx1 = 200 * (Math.sin(m * 30 * deg))
                let yy1 = 200 * (Math.cos(m * 30 * deg))
                ctx.moveTo((300 + xx), (300 - yy));
                ctx.lineTo((300 + xx1), (300 - yy1))
            }

            move(Seconds, SecondsR)
            move(Minutes, MinutesR)
            ctx.fill()
            ctx.stroke()
        }, 1000)


    </script>
</body>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值