본문 바로가기
Javascript/GMA(2302~)

23.04.19 자바스크립트 내장객체(*Date 객체) - 아날로그 시계 만들기

by hyerin1201 2023. 4. 19.

Date객체를 활용하여 아날로그 시계만들기 예제

 

HTML body 영역

<body>
  <div class="clock">
    <div class="lineHour"></div>
    <div class="lineMin"></div>
    <div class="lineSec"></div>
  </div>
</body>

 

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.clock {
  width: 400px;
  height: 400px;
  border: 3px solid  rgb(245, 220, 188);
  border-radius: 50%;
  background-color: antiquewhite;

  position: relative;
}

.lineHour {
  width: 10px;
  height: 150px;
  background-color: #77683e;

  position: absolute;
  left: calc(50% - 5px);
  top: calc(50% - 150px);
  transform-origin: bottom;
}
.lineMin {
  width: 4px;
  height: 200px;
  background-color: #9c9274;

  position: absolute;
  left: calc(50% - 2px);
  top: calc(50% - 200px);
  transform-origin: bottom;
}
.lineSec {
  width: 2px;
  height: 200px;
  background-color: #977e46;

  position: absolute;
  left: calc(50% - 1px);
  top: calc(50% - 200px);
  transform-origin: bottom;
}

 

Javascript

setInterval(()=> {
  const now = new Date();

  const h = now.getHours();
  const m = now.getMinutes();
  const s = now.getSeconds();
  
  const degH = h * (360 / 12) + m * (360 / 12 / 60);
  const degM = m * (360 / 60);
  const degS = s * (360 / 60);
  
  const elementH = document.querySelector(".lineHour");
  const elementM = document.querySelector(".lineMin");
  const elementS = document.querySelector(".lineSec");
  
  elementH.style.transform = `rotate(${degH}deg)`;
  elementM.style.transform = `rotate(${degM}deg)`;
  elementS.style.transform = `rotate(${degS}deg)`;
}, 1000);

 

완성이미지