使用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时钟特效专题

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

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!