网页自动显示时间的时钟

简介

用html,JavaScript完成一个简易的自走时钟
主要参考:https://www.cnblogs.com/lemoncool/p/8527334.html
该教程后期帮助较大,可以先试着自己做,遇到难题再看该教程,而且其讲解也比较细致。

设置画布

首先在html中设置一个画布。因为只是简单的一个画布,直接规定高宽即可。

<canvas id="clock" width="650" height="650" style="border:1px solid #d3d3d3;"></canvas>

画圆

笔者就以自己其中一个圆举例

	ctx.beginPath(); //开始绘画
    ctx.arc(0,0,300,0,2*Math.PI);
    ctx.fillStyle="#000000";
    ctx.fill(); //设置颜色后填充
    ctx.stroke(); //与beginPath()一起不可缺少
设置刻度和数字

该步是设置刻度,设置数字的时候可以运用圆的相关知识进行更快的设置,方法和思维差别不大就不列举出来了。

   function scale()
    {
    var i;
    for(i=0;i<360;i++)
    {
        if(i%6 === 0)
        {
            ctx.lineWidth=2;

            if(i%30 === 0)
                ctx.lineWidth = 8;

            ctx.beginPath();
            ctx.moveTo(0,-280);
            ctx.lineTo(0,-260);
            ctx.strokeStyle="#000000";
            ctx.stroke();

            ctx.beginPath();
            ctx.moveTo(0,260);
            ctx.lineTo(0,280);
            ctx.strokeStyle="#000000";
            ctx.stroke();

            ctx.rotate(6*Math.PI/180);
        }
    }
    }
定义指针如何走

该步的难题在于如何通过save()和restore()做到更新画布的效果从而达到更新指针位置实现自动走的效果。

 function Hour(hour)
    {
        ctx.save();
        ctx.beginPath();
        var rad = 2 * Math.PI / 12 * hour;
        ctx.lineWidth = 10;
        ctx.rotate(rad);
        ctx.moveTo(0,40);
        ctx.lineTo(0,-90);
        ctx.strokeStyle="#000000";
        ctx.stroke();
        ctx.restore();
    }
最后设置一个函数整合起来

其中setInterval(“draw()”,1000)是用来规定多久执行一次该函数,因为单位是ms,所以一秒更新一次就设置成1000。

    function draw()
    {
        ctx.clearRect(0, 0, 650, 650);
        var time = new Date();
        var hour = time.getHours();
        var minute = time.getMinutes();
        var second = time.getSeconds();
        circle();
        number();
        scale();
        Hour(hour);
        Minute(minute);
        Second(second);
        ctx.restore();
    }
    setInterval("draw()",1000);
效果如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值