clock

REF: JavaScript30

先備知識

原理

  • transform: rotate:指針旋轉
  • transition-timing-function:指針走動效果
  • Date():指針依照現在時間旋轉到適當位置

範例

.clock
 .clock-face
  .hand.hour-hand
  .hand.min-hand
  .hand.second-hand
html
 background: #FFFFF0
 font-family: 'helvetica neue'
 text-align: center
 font-size: 10px

body
 font-size: 2rem
 display: flex
 flex: 1
 min-height: 100vh
 align-items: center

.clock
 width: 30rem
 height: 30rem
 border: 8px solid #086788
 border-radius: 50%
 margin: 50px auto
 position: relative
 padding: 2rem
 box-shadow: 3px 3px 5px #ccc

.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: #2EC4B6
 position: absolute
 top: 50%
 //指針以右邊為基點旋轉
 transform-origin: 100%
 //default: 50% 基點為中心
 transform: rotate(90deg)
 transition: all 0.05s
 transition-timing-function: cubic-bezier(0, 1.03, 0, 2.09)
const secondHand=document.querySelector(".second-hand");
const minHand=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; //offset default 90 deg
 
 const mins=now.getMinutes();
 const minsDegrees=((mins/60)*360)+90;
 
 const hours=now.getHours();
 const hoursDegrees=((hours/12)*360)+90;
 
 secondHand.style.transform=`rotate(${secondsDegrees}deg)`;
 minHand.style.transform=`rotate(${minsDegrees}deg)`;
 hourHand.style.transform=`rotate(${hoursDegrees}deg)`;
 
 console.log(seconds);
 
 //59-60時指針會快速繞一圈(角度計算的關係),所以停止transition
 if(seconds==59){
 secondHand.style.transition="0s";
 }
 if(mins==59){
 minHand.style.transition="0s";
 }
 if(hours==11){
 hourHand.style.transition="0s";
 }
 
}

//run every second
setInterval(setDate, 1000);

Display

CODEPEN

2 Replies to “clock”

  1. Wonderful beat ! I wish to apprentice while you amend your website,
    how could i subscribe for a blog website? The account aided me a acceptable deal.
    I had been a little bit acquainted of this your broadcast provided bright clear idea

Leave a Reply

Your email address will not be published. Required fields are marked *