JavaScript30-2
javascript, css 활용하여 시계만들기(JS + CSS Clock)
목표: 현재 시간을 아날로그 시계로 구현
과정
- 시계바늘 중심위치 잡기(css)
- 현재시간 가져와서 맞는각도 시계바늘에 넣기(js)
코드분석
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS + CSS Clock</title>
<style>
html {
background: #018DED url(http://unsplash.it/1500/1000?image=881&blur=5);
background-size: cover;
font-family: 'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
margin: 0;
font-size: 2rem;
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
}
.clock {
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
margin: 50px auto;
position: relative;
padding: 2rem;
box-shadow:
0 0 0 4px rgba(0,0,0,0.1),
inset 0 0 0 3px #EFEFEF,
inset 0 0 10px black,
0 0 10px rgba(0,0,0,0.2);
}
.clock-face {
position: relative;
width: 100%;
height: 100%;
transform: translateY(-3px); /* account for the height of the clock hands */
}
.hand {
width: 50%;
height: 6px;
background: black;
position: absolute;
top: 50%;
transform-origin: 100%;
transform:rotate(90deg);
transition:all 0.05s;
transition-timing-function:cubic-bezier(0.1, 2.7, 0.58, 1);
}
</style>
</head>
<body>
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
</body>
</html>
const secondHand = document.querySelector('.second-hand');
const minsHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');
function setDate(){
const now = new Date();
const seconds = now.getSeconds();
const secondsDegrees = ((seconds / 60) * 360) + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
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)`;
console.log(seconds)
}
setInterval(setDate, 1000);
setDate();
마지막 코드 setDate()
는 로드됬을 때 바로 함수 한 번 실행함을 나타낸다.
그 뒤부터는 setInterval이 실행.
각도(끝에 +90은 12시방향으로 돌린것)
mins: 분에 해당하는 각도 (mins/60) * 360하고 초에 해당하는 각도만큼 더해줌(한 칸에 6이어서 * 6)
hour: 시에 해당하는 각도 (hour/12) * 360하고 시간지날수록 시침도 조금씩 움직이니까 (mins/60) *30 더해줌(시는 한 칸에 30)
알게 된 내용 & 찾아 본 내용:
transform-origin
: 회전중심(원점, 기준점) 지정
- 100%으로 가장 오른쪽으로 잡고rotate(90deg)
90도 돌려서 시계바늘을 12시방향으로 맞춤transition-timing-function
: cubic-bezier는 네 점에 의해 정의
- 그래프로 제공 http://cubic-bezier.com
참고
[transform-origin:] https://www.tabmode.com/homepage/transform-origin.html
[transition-timing-function:] https://www.codingfactory.net/10942