使用js和canvas写一个时钟,供大家参考,具体内容如下

使用js和canvas实现时钟效果

<!DOCTYPE html>`
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id='canvas' width='600' height='600' style="border: 1px solid red;"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
    let canvas = document.querySelector("#canvas");
    let ctx = canvas.getContext("2d");
    let deg = Math.PI / 180;

    let HourR = 100;
    let MinutesR = 135;
    let SecondsR = 170;
    setInterval(function () {

      canvas.width = canvas.width;
      ctx.arc(300, 300, 200, 0, Math.PI * 2)
      ctx.fillStyle = 'rgba(10,100,30,0.2)'
      ctx.strokeStyle = 'red'
      //获取当前时间
      let dt = new Date()
      let Hour = dt.getHours()
      let Minutes = dt.getMinutes()
      let Seconds = dt.getSeconds()
      //时钟
      ctx.moveTo(300, 300);
      let xx = HourR * (Math.sin(Hour * 30 * deg))
      let yy = HourR * (Math.cos(Hour * 30 * deg))
      ctx.lineTo((300 + xx), (300 - yy))
      //分钟和秒钟
      function move(time, R) {
        ctx.moveTo(300, 300);
        xx = R * (Math.sin(time * 6 * deg))
        yy = R * (Math.cos(time * 6 * deg))
        ctx.lineTo((300 + xx), (300 - yy))
      }
      //小时指针
      for (let m = 0; m < 12; m++) {
        let xx = 190 * (Math.sin(m * 30 * deg))
        let yy = 190 * (Math.cos(m * 30 * deg))
        let xx1 = 200 * (Math.sin(m * 30 * deg))
        let yy1 = 200 * (Math.cos(m * 30 * deg))
        ctx.moveTo((300 + xx), (300 - yy));
        ctx.lineTo((300 + xx1), (300 - yy1))
      }

      move(Seconds, SecondsR)
      move(Minutes, MinutesR)
      ctx.fill()
      ctx.stroke()
    }, 1000)


  </script>
</body>

</html>

更多JavaScript时钟特效点击查看:JavaScript时钟特效专题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
js,canvas,时钟

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“使用js和canvas实现时钟效果”

暂无“使用js和canvas实现时钟效果”评论...