canvas 时钟

144 阅读1分钟
时钟 * { padding: 0; margin: 0; } body { background-color: #cccccc; } #canvas { background-color: #ffffff; }
<script>
  window.onload = function () {
    let canvas = document.getElementById('canvas');
    if (canvas.getContext) {
      let ctx = canvas.getContext('2d');
      setInterval(()=>{
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        move();
      }, 1000)

      function move() {
        // 表盘
        ctx.save();               
        ctx.lineWidth = 5;
        ctx.translate(300, 300);   // 圆心(原点)位置
        ctx.beginPath();
        ctx.arc(0, 0, 100, 0, 360*Math.PI/180);
        ctx.stroke();
        ctx.restore();            
        
        // 时针刻度
        ctx.save();
        ctx.translate(300, 300);
        for (let i=0; i<12; i++) {
          ctx.rotate(30 * Math.PI/180);
          ctx.beginPath();
          ctx.arc(0, 85, 3, 0, 360*Math.PI/180);
          ctx.fill();
        }
        ctx.restore();

        // 分针刻度
        ctx.save();
        ctx.translate(300, 300);
        for (let i=0; i<60; i++) {
          if (i%5 != 0) {
            ctx.fillStyle = "#ccc";
            ctx.beginPath();
            ctx.arc(0, 85, 1, 0, 360*Math.PI/180);
            ctx.fill();
          }
          ctx.rotate(6 * Math.PI/180);
        }
        ctx.restore();

        // 获取时、分、秒
        let date = new Date();
        let s = date.getSeconds();
        let m = date.getMinutes() + s/60;
        let h = date.getHours() + m/60;
        h > 12 ? h = h-12 : h = h;      // 12小时制

        // 时针
        ctx.save();
        ctx.translate(300, 300);
        ctx.rotate((-90 * Math.PI/180) + (h * 30 * Math.PI/180));      // 指针移动到270° 也就是 12点位置 + 时针旋转角度
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(-20, 0);
        ctx.lineTo(60, 0);
        ctx.stroke();
        ctx.restore();

        // 分针
        ctx.save();
        ctx.translate(300, 300);
        ctx.rotate((-90 * Math.PI/180) + (m * 6 * Math.PI/180));      // 指针移动到-90° 也就是 12点位置 + 分针旋转角度
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.moveTo(-28, 0);
        ctx.lineTo(65, 0);
        ctx.stroke();
        ctx.restore();

        // 秒针
        ctx.save();
        ctx.translate(300, 300);
        ctx.rotate((-90 * Math.PI/180) + (s * 6 * Math.PI/180));
        ctx.lineWidth = 2;
        ctx.strokeStyle = "#D40000";
        ctx.beginPath();
        ctx.moveTo(-30, 0);
        ctx.lineTo(75, 0);
        ctx.stroke();
        ctx.restore();

        // 表中心
        ctx.save();
        ctx.translate(300, 300);
        ctx.fillStyle = "#D40000";
        ctx.beginPath();
        ctx.arc(0, 0, 7, 0, 360*Math.PI/180);
        ctx.fill();
        ctx.restore();
      }

    }
  }
</script>