利用canvas制作时钟表

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas画布绘制时钟</title>
    <style>
      body{background: black}
        #c1{background: white}
        span{color:white;}
    </style>
</head>
<body>
<canvas id="c1" width="400" height="400">
    <span>
        不支持canvas浏览器
    </span>
</canvas>
<script>
    var oC= document.querySelector("canvas");
    var oGC=oC.getContext('2d');
    //浏览器打开时停滞一秒才会运行,解决办法是封装成一个函数,开始时进行调用,在开始计时器。
    //进行画布的反复绘制,从而达到时针变化的效果。
    setInterval(function(){
        oGC.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
        //保存路径
        oGC.save();
        //大圆和小刻度
        for(var i=0;i<60;i++)
        {
            oGC.beginPath();
            oGC.moveTo(200,200);
            oGC.arc(200,200,100,i*6*Math.PI/180,(i+1)*6*Math.PI/180,false);
            oGC.stroke();
        }
        oGC.beginPath();
        oGC.moveTo(200,200);
        oGC.arc(200,200,90,0,360*Math.PI/180,false);
        oGC.fillStyle="white";
        oGC.fill();
        //大刻度
        for(var i=0;i<12;i++) {
            oGC.beginPath();
            oGC.moveTo(200,200);
            oGC.arc(200,200,100,i*30*Math.PI/180,(i+1)*30*Math.PI/180,false);
            oGC.lineWidth='2';
            oGC.stroke();
        }
        oGC.beginPath();
        oGC.fillStyle="#fff";
        oGC.arc(200,200,80,0,360*Math.PI/180,false)
        oGC.fill();
        //时间的换算
        var oD=new Date();
        //canvas起点是3点位置所以-90是12点的位置。小时的转化是由小时和分钟进行转化。1小时为30度,30度为60分钟,则1分钟为0.5度
        var oH=Math.floor(oD.getHours()*30-90+oD.getMinutes()/2)
        //同理
        var oM=Math.floor(oD.getMinutes()*6-90+oD.getSeconds()/10);
        var oS=oD.getSeconds()*6-90;
        //时针的绘制
        oGC.beginPath();
        oGC.moveTo(200,200);
        oGC.arc(200,200,40,oH*Math.PI/180,oH*Math.PI/180,false);
        oGC.lineWidth='4';
        oGC.strokeStyle="pink";
        oGC.stroke();
        //分针的绘制
        oGC.beginPath();
        oGC.moveTo(200,200);
        oGC.arc(200,200,60,oM*Math.PI/180,oM*Math.PI/180,false);
        oGC.lineWidth='3';
        oGC.strokeStyle="yellow";
        oGC.stroke();
        //秒针的绘制
        oGC.beginPath();
        oGC.moveTo(200,200);
        oGC.arc(200,200,80,oS*Math.PI/180,oS*Math.PI/180,false);
        oGC.lineWidth='2';
        oGC.strokeStyle="green";
        oGC.stroke();
  oGC.restore();
    },1000)

</script>
</body>
</html>

注意:1.圆的绘制:arc(x,y,半径,起始弧度,结束弧度,旋转方向)

           3.canvas的圆的起点在3点钟的位置。

           2.旋转方向:顺时针(默认:false)、逆时针(true)。

          4.时间转化。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值