Clock in our life can be seen everywhere, today we use JS to make a simple clock, first look at the effect

rendering

On the code (annotated very detailed 🤞)

<div id="box">
    <div class="hour"></div>
    <div class="min"></div>
    <div class="sec"></div>
  </div>
Copy the code
  #box {
      width: 610px;
      height: 610px;
      margin: 0 auto;
      background: url('/ dial 1. PNG') no-repeat center;
      position: relative;
    }

    #box div {
      position: absolute;
    }

    .hour {
      width: 15px;
      height: 300px;
      background: url('/ clockwise. PNG') no-repeat;
      top: 110px;
      left: 297px;
      background-size: cover;
      /* Change the position of the converted element */
      transform-origin: 50% 68%;
    }

    .min {
      width: 17px;
      height: 300px;
      background: url('/ minute hand. PNG') no-repeat;
      top: 140px;
      left: 297px;
      background-size: cover;
      transform-origin: 50% 58%;
    }

    .sec {
      width: 15px;
      height: 160px;
      background: url('/ second hand. The PNG') no-repeat;
      top: 193px;
      left: 297px;
      background-size: cover;
      transform-origin: 50% 75%;
    }
Copy the code
 var sec = document.querySelector('.sec');
    var min = document.querySelector('.min');
    var hour = document.querySelector('.hour');
    var getTime = function () {
      // Get the current time
      var d = new Date(a);// Return the hour of the Date object (0 ~ 23)
      var h = d.getHours();
      // Return the minutes of the Date object (0 ~ 59)
      var m = d.getMinutes();
      // Return the number of seconds of the Date object (0 ~ 59)
      var s = d.getSeconds();
      // The second hand moves at dial time
      hour.style.transform = "rotate(" + (h * 30 + m * 0.5) + "deg)";
      min.style.transform = "rotate(" + (m * 6 + s * 0.1) + "deg)";
      sec.style.transform = "rotate(" + s * 6 + "deg)";
    }
    setInterval(getTime, 10);
Copy the code

material

  • The dial

  • Hour hand, minute hand, second hand