JavaScript canvas动画实现时钟效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript canvas动画实现时钟效果

crazy的蓝色梦想   2020-05-17 我要评论

本文实例为大家分享了canvas动画实现时钟效果的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>时钟特效</title>
</head>
<body>
  <canvas width="150" height="150" id="canvas"></canvas>
</body>
</html>
<script>
  clock();// 显示
  setInterval(clock,1000);// 每一秒重绘一次,达到转动效果
  function clock(){
    var now = new Date();// 得到当前日期与时间
    var second = now.getSeconds(),
      min = now.getMinutes(),
      hour = now.getHours();// 得到时分秒
      hour = hour > 12?hour-12:hour;
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0,0,150,150);// 初始化画布
    ctx.save();
    ctx.translate(75,75);// 平移坐标原点
    ctx.scale(0.4,0.4);//缩放效果
    ctx.rotate(-Math.PI/2);// 将x轴旋转-90
    ctx.strokeStyle = 'black';
    ctx.fillStyle = 'black';
    ctx.lineWidth = 8;
    ctx.lineCap = 'round';

    // 显示时针刻度
    ctx.save();
    ctx.beginPath();
    for(var i = 0;i<12;i++)
    {
      ctx.rotate(Math.PI/6);
      ctx.moveTo(100,0);
      ctx.lineTo(120,0);
    }
    ctx.stroke();
    ctx.closePath();
    ctx.restore();// 恢复
    ctx.save();
    
    // 显示秒针刻度
    ctx.beginPath();
    ctx.lineWidth = 5;
    for(var i = 0;i < 60; i++)
    {
      if(i % 5 != 0)
      {
        ctx.moveTo(117,0);
        ctx.lineTo(120,0);
      }
      ctx.rotate(Math.PI/30);// 转6度
    }
    ctx.stroke();
    ctx.closePath();
    ctx.restore();// 恢复
    ctx.save();

    // 绘制时针
    ctx.beginPath();
    ctx.rotate((Math.PI / 6)*hour + (Math.PI/360)*min + (Math.PI /21600)*second)//时针当前指向的位置
    ctx.lineWidth = 14;
    ctx.moveTo(-20,0);
    ctx.lineTo(75,0);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();//恢复
    ctx.save();

    // 绘制分针
    ctx.beginPath();
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 10;
    ctx.rotate((Math.PI/30)*min + (Math.PI/1800)*second);// 分针当前的位置
    ctx.moveTo(-28,0);
    ctx.lineTo(102,0);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();//恢复
    ctx.save();


    // 绘制秒针
    ctx.beginPath();
    ctx.rotate(Math.PI/30*second);
    ctx.strokeStyle = '#D40000';
    ctx.lineWidth = 6;
    ctx.moveTo(-30,0);
    ctx.lineTo(83,0);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();//恢复
    ctx.save();

    //绘制表框
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#325Fa2';
    ctx.arc(0,0,142,0,Math.PI*2,true);//半径142
    ctx.stroke();
    ctx.closePath();
    ctx.restore()//恢复
    ctx.restore()//恢复


  }
</script>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们