實現起來並不複雜,只需對最左和最右的小球進行關鍵幀動畫處理,同時註意應該將繩子與小球作為一個整體,以左邊小球為例: .left-ball.ball-wrapper { transform-origin: center top; animation: left-ball-swing 4s 0s inf ...
最近在練習CSS3的關鍵幀動畫(keyframes),於是做了一個簡單的牛頓擺(聽名字可能陌生,但你一定見過它):
先上代碼(老版本IE可能存在相容性問題):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> html, body { height: 100%; margin: 0px; padding: 0px; } .main-container { display: flex; justify-content: center; align-items: center; height: 100%; background-color: #d7c8d0; } .swing-container { width: 500px; height: 400px; display: flex; flex-wrap: wrap; } .roof { width: 100%; height: 20px; background-color: #18619b; } .ball-wrapper { flex-basis: 100px; height: 380px; display: flex; align-items: center; flex-direction: column; } .ball { height: 100px; width: 100px; text-align: center; line-height: 90px; border-radius: 50px; background-color: #edcb66; } .rope { background: black; width: 2px; height: 280px; } .left-ball.ball-wrapper { transform-origin: center top; animation: left-ball-swing 4s 0s infinite normal; } .right-ball.ball-wrapper { transform-origin: center top; animation: right-ball-swing 4s 2s infinite normal; } @keyframes left-ball-swing { 0% { transform: rotate(0deg); animation-timing-function: ease-out; } 25% { transform: rotate(90deg); animation-timing-function: ease-in; } 50% { transform: rotate(0deg) } 100% {} } @keyframes right-ball-swing { 0% { transform: rotate(0deg); animation-timing-function: ease-out; } 25% { transform: rotate(-90deg); animation-timing-function: ease-in; } 50% { transform: rotate(0deg) } 100% {} } </style> </head> <body> <div class="main-container"> <div class="swing-container"> <div class="roof"> </div> <div class="left-ball ball-wrapper"> <div class="rope"></div> <div class="ball">快</div> </div> <div class="ball-wrapper"> <div class="rope"></div> <div class="ball">點</div> </div> <div class="ball-wrapper"> <div class="rope"></div> <div class="ball">去</div> </div> <div class="ball-wrapper"> <div class="rope"></div> <div class="ball">看</div> </div> <div class="right-ball ball-wrapper"> <div class="rope"></div> <div class="ball">書</div> </div> </div> </div> </body> </html>實現起來並不複雜,只需對最左和最右的小球進行關鍵幀動畫處理,同時註意應該將繩子與小球作為一個整體,以左邊小球為例:
.left-ball.ball-wrapper {
transform-origin: center top;
animation: left-ball-swing 4s 0s infinite normal;
}
@keyframes left-ball-swing {
0% {
transform: rotate(0deg);
animation-timing-function: ease-out;
}
25% {
transform: rotate(90deg);
animation-timing-function: ease-in;
}
50% {
transform: rotate(0deg)
}
100% {}
}
以繩子的起點為圓心,擺動共4秒:
0%--25%(第一秒): 順時針旋轉90度,速度為ease-out(逐漸變緩,因為動能轉化為勢能到了最高點速度為0)
25%--50%(第二秒): 返回到0度,即逆時針旋轉了90度,速度為ease-in,勢能變為動能
50%--100%(後兩秒):不做變化(這兩秒是右邊小球在擺動)
That'it,最後來看效果圖:
感謝閱讀,o(* ̄▽ ̄*)o
原創文章,轉載請註明出處。