이번에는 자바스크립트와 CSS스타일을 이용해서 간단하게 시계를 만들어 보려고 한다.
1 2 3 4 5 6 7 8 | <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> <!-- hour,min,second 시,분,초 --> | cs |
일단 html의 구조는 위와 같다.
시,분,초를 각각 나눠서 html div 태그로 만들어 두고 중심을 맞춰야하기 때문에 'hand'라는 클라스를 공통적으로 적용한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | .hand { width:50%; height:6px; background:black; position: absolute; top:50%; transform-origin: 50%; transform:rotate(90deg); transition: all 0.5s; transition-timing-function:cubic-bezier(0.1, 2,7, 0.58 ,1); } /*시,분,초의 중심을 맞추기위해서는 transfrom-origin의 값을 변경해준다. 위 html에서 'hand'라는 같은 클래스를 적용해놨기 때문에 시,분,초는 동일한 위치에서 시작된다.*/ | cs |
css의 .hand는 transfrom-origin으로 시,분,초의 시작점을 동일시하게 맞춘다.
tansition속성으로 시간과 움직임을 부여한다. 그래야 시계가 째깎째깍 가는 모습으로 침들이 움직일 것이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script> 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); 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.getMinutes(); const hourDegrees = ((hour / 12) * 360) + ((mins/60)*30) + 90; hoursHand.style.transform = `rotate(${hourDegrees}deg)`; } setInterval(setDate,1000); setDate(); </script> | cs |
시,분,초를 setDate함수에 만들어두고 setInterval로 1초마다 함수가 작동하도록 설정해 두었습니다.