[JavaScript 30 Days Challenge] JS and CSS Clock

yuza🍊·2021년 10월 2일
0
post-thumbnail

DAY 2-JS and CSS Clock

CODE

기본 구현 사항: 시계의 시침, 분침, 초침이 현재 시각에 맞춰 움직이도록 구현하기

1) 초, 분, 시침을 선택하여(document.querySelector 사용) 변수에 할당

const secondHand = document.querySelector(".second-hand");
const minsHand = document.querySelector(".min-hand");
const hourHand = document.querySelector(".hour-hand");

2) setClock 함수 선언 후 변수 now에 Date 객체 할당

function setClock() {
  const now = new Date();
}

3) Date 객체에서 현재 초 정보를 추출(getSeconds() 사용)하여 변수 seconds에 할당, 초를 60으로 나눈 뒤 360을 곱하여 현재 초가 360도 중 몇 도를 차지하는지 계산한 뒤, 90을 더함

  • 90을 더하는 이유: 시계의 침의 기본 위치는 90도(세로로 세워진 형태)를 띄고 있기 때문
    그리고 초침의 style의 transform 속성에 접근하여 해당 시점에서 초침이 가져야 할 각도만큼 rotate 되도록 설정한다.
  const seconds = now.getSeconds();
  const secondsDegrees = (seconds / 60) * 360 + 90;
  secondHand.style.transform = `rotate(${secondsDegrees}deg)`;

4) 분침, 시침도 동일한 방법으로 구현 - 시침은 현재 시간을 60이 아닌 12로 나누어야 함

  const mins = now.getMinutes();
  const minsDegrees = (mins / 60) * 360 + (seconds / 60) * 6 + 90;
  minsHand.style.transform = `rotate(${minsDegrees}deg)`;

  const hour = now.getHours();
  const hourDegrees = (hour / 12) * 360 + (mins / 60) * 30 + 90;
  hourHand.style.transform = `rotate(${hourDegrees}deg)`;

5) setInterval 함수(지정한 시간만큼의 간격을 두고 콜백 함수를 실행하게 하는 함수)를 사용하여 setClock 함수를 1000ms 당 한 번 실행하도록 함

setInterval(setClock, 1000);

내가 추가한 기능: 시계 테두리의 색깔을 시침, 분침, 초침의 각도가 변화함에 따라 조금씩 달라질 수 있도록 구현

1) 시계 테두리를 이루는 원을 변수에 할당

const clock = document.querySelector(".clock");

2) 시계 테두리의 style 속성에 접근, border의 색상 rgb를 이루는 세 개의 값에 시침, 분침, 초침의 각도 값을 할당

  clock.style.border = `20px solid rgb(${hourDegrees}, ${minsDegrees}, ${secondsDegrees})`;

What I Learned

transform과 transform-origin

  • 처음 시계의 침들은 다음과 같이 누워있는 형태로 존재한다.

이 침들을 90도로 세우기 위해서는 transform: rotate(90deg) 속성을 부여해야 한다. 하지만 정작 해당 속성을 부여하면?

이렇게 내가 원하는 형태로 배치되지 않는다. 이는 transform 속성이 요소의 50%에 해당하는 위치에서 적용되기 때문이다. 즉, 검은 침의 중앙에서 rotate(90deg)가 적용되는 것이다. 검은 침의 오른쪽 끝에서 rotate(90deg)가 적용되기를 원한다면 transform-origin: 100%; 속성을 부여해야 한다. 그러면

이렇게 원하는 대로 적용이 된다.

profile
say hi to the world

0개의 댓글