- 프로젝트 개요
- JavaScript와 CSS를 활용한 아날로그 시계
- JavaScript Code
const secondHand = document.querySelector('.second-hand');
const minuteHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand')
function setDate() {
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes();
const hours = now.getHours();
const secondsDegrees = ((seconds / 60) * 360) + 90;
const minutesDegrees = ((minutes / 60) * 360) + (seconds / 10) + 90;
const hoursDegrees = ((hours / 12) * 360) + (minutes / 2) + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
minuteHand.style.transform = `rotate(${minutesDegrees}deg)`;
hourHand.style.transform = `rotate(${hoursDegrees}deg)`;
console.log(seconds);
console.log(secondsDegrees);
}
setInterval(setDate, 1000);
- setDate 함수
- Date 객체를 생성하여 현재 시각을 불러온 후 각 변수에 초, 분, 시간 단위로 저장
- 각 Degrees 변수에 시간에 따른 각도를 저장
- 시계바늘의 시작점이 270도이므로 마지막에 +90
- 추가적으로 분침은 10초당 1도, 시침은 2분당 1도 움직이도록 설정
- CSS의 hand 클래스를 transform
- setInterval 함수를 사용하여 setDate 함수를 1초에 한 번씩 실행하도록 함
'Vanilla JS' 카테고리의 다른 글
[Project] CSS 변수 제어 (0) | 2022.02.04 |
---|---|
[Project] 드럼 패드 (0) | 2022.01.31 |