您当前的位置: 首页 >  html

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

html:canvas画布绘图简单入门-绘制时钟-3

彭世瑜 发布时间:2022-01-01 09:53:46 ,浏览量:3

canvas示例系列:

  • html:canvas画布绘图简单入门-1
  • html:canvas画布绘图简单入门-2
  • html:canvas画布绘图简单入门-绘制时钟-3
  • html:canvas画布绘图简单入门-刮刮乐-4
示例10:绘制时钟

在这里插入图片描述



    
        let canvas = document.querySelector('#canvas');
        let ctx = canvas.getContext('2d');
        let width = canvas.width
        let height = canvas.height

        // 绘制内容区域相对画布的大小 80%
        let scale = 0.8;

        // 计算半径
        let radius = Math.floor(Math.min(width, height) * scale * 0.5);
        console.log('radius', radius);

        // 绘制外边框
        // ctx.beginPath();
        // ctx.strokeRect(0, 0, width, height);
        // ctx.closePath()


        // 绘制时钟刻度
        function drawClockScale({
            number = 12,
            strokeStyle = 'black',
            lineWidth = 3,
            lineLength = 20,
        }) {
            ctx.save();

            ctx.strokeStyle = strokeStyle;
            ctx.lineWidth = lineWidth;
            let rotateAngle = (360 / number);

            for (let i = 0; i  12) {
                hour = hour - 12
            }

            // 绘制时针
            ctx.save();
            ctx.beginPath();
            ctx.rotate((Math.PI / 180) * ((360 / 12) * hour + (360 / 12 / 60) * minute + (360 / 12 / 60 / 60) *
                second));
            ctx.strokeStyle = "red";
            ctx.lineWidth = 8;
            ctx.moveTo(-20, 0);
            ctx.lineTo(radius - 50, 0);
            ctx.stroke();
            ctx.closePath()
            ctx.restore();

            // 绘制圆心
            ctx.beginPath();
            ctx.fillStyle = "grey";
            ctx.lineWidth = 10;
            ctx.arc(0, 0, 10, 0, Math.PI / 180 * 360);
            ctx.fill();
            ctx.closePath()

            // 绘制圆
            ctx.beginPath();
            ctx.strokeStyle = "grey";
            ctx.lineWidth = 10;
            ctx.arc(0, 0, radius, 0, Math.PI / 180 * 360);
            ctx.stroke();
            ctx.closePath()
            
            ctx.restore();
        }

        // 每隔1秒重绘一次
        setInterval(() => {
            drawClock();
        }, 1000)
    

需要修改坐标轴之前,最好把当前状态保存,绘制完成后再恢复

在线demo: https://mouday.github.io/front-end-demo/canvas/canvas-clock.html

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.1007s