时钟HTML代码段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>rotate</title>
</head>
<body>
<canvas id='canvas' width="300" height="300"></canvas>
<script> 
   function rotateFun(){
      var now= new Date();//获取当前时间对象,对以后指针旋转很重要

      var ctx=document.getElementById("canvas").getContext("2d");//取的画布环境

      ctx.clearRect(0,0,800,600);//在开始之前都要清空画布,因为不清空就会所有的痕迹在画布上显示

      ctx.save();//第一个保存状态
      ctx.fillStyle='rgba(20,20,20,0.2)';
      ctx.fillRect(0,0,800,600);
      ctx.translate(150,150);//平移画布中心到中心 
      
      //画12个小时
      ctx.save();
      for (var i = 0; i < 12; i++) {
        ctx.strokeStyle='black';
        ctx.rotate(2*Math.PI/12);
        ctx.moveTo(120,0);
        ctx.lineTo(100,0);
        ctx.lineWidth=8;
        ctx.stroke();
      }
      ctx.restore(); 

      //画60个分钟
      ctx.save();
      for (var i = 0; i <60 ;i++) {
        ctx.strokeStyle='black';
        ctx.rotate(2*Math.PI/60);
        ctx.moveTo(115,0);
        ctx.lineTo(105,0);
        ctx.lineWidth=2;
        ctx.stroke();
      }
      ctx.restore();
      
      var hour=now.getHours();
      var min=now.getMinutes();
      var sec=now.getSeconds();

      //画秒针
      ctx.save();
      ctx.beginPath();
      ctx.rotate(sec*Math.PI/30);
      ctx.strokeStyle='black';
      ctx.lineWidth=4;
      ctx.moveTo(0,30);
      ctx.lineTo(0,-112);
      ctx.stroke();
      ctx.closePath();
      ctx.restore();

      //画分钟
      ctx.save();
      ctx.beginPath();
      ctx.rotate(min*Math.PI/30+sec*Math.PI/1800);
      ctx.strokeStyle='black';
      ctx.lineWidth=6;
      ctx.moveTo(0,28);
      ctx.lineTo(0,-83);
      ctx.stroke();
      ctx.closePath();
      ctx.restore();

      //画时钟
      ctx.save();
      ctx.beginPath();
      ctx.rotate(hour*Math.PI/6+min*Math.PI/360+sec*Math.PI/21600);
      ctx.strokeStyle='black';
      ctx.lineWidth=8;
      ctx.moveTo(0,26);
      ctx.lineTo(0,-63);
      ctx.stroke();
      ctx.closePath();
      ctx.beginPath();
      ctx.strokeStyle='blue';
      ctx.arc(0,0,126,0,2*Math.PI);
      ctx.stroke();
      ctx.closePath();
      ctx.restore();
      ctx.restore();

      window.requestAnimationFrame(rotateFun);
   }

   rotateFun();
</script>
</body>
</html>

浏览后显示的效果为:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值