HyperFrames 的 CSS 動畫
HyperFrames 可透過其 css 執行時期適配器來搜尋 CSS 關鍵幀動畫。將此用於簡單重複的主題、背景運動、微光、光暈、遮罩及非序列裝飾。
對於場景編排,GSAP 通常更清晰。當動畫屬於單一元素且具有固定持續時間時,CSS 動畫表現最佳。
合約
- 在執行時期初始化完成之前,將動畫元素放入 DOM。
- 為計時元素提供
data-start值,使本地動畫時間與片段匹配。 - 使用有限的
animation-duration與animation-iteration-count,因為負值延遲的備用方案無法在沒有 WAAPI 支援的 CSS 動畫環境中表示無界持續時間。 - 偏好使用
animation-fill-mode: both,以便在主動運動前後,搜尋狀態能保持住。 - 避免依賴實際時鐘的 JavaScript、懸浮觸發的狀態,以及依賴使用者事件的類別切換。
此適配器會發現具有計算後 animation-name 的元素,在可用時搜尋其瀏覽器 Animation 控制句柄,並以負值 animation-delay 暫停作為備用。
基本模式
<div
id="pulse-ring"
class="clip pulse-ring"
data-start="0"
data-duration="4"
data-track-index="2"
></div>
<style>
.pulse-ring {
width: 280px;
height: 280px;
border: 4px solid rgba(255, 255, 255, 0.7);
border-radius: 50%;
animation-name: pulse-ring;
animation-duration: 1200ms;
animation-timing-function: cubic-bezier(0.2, 0, 0, 1);
animation-iteration-count: 3;
animation-fill-mode: both;
}
@keyframes pulse-ring {
from {
opacity: 0;
transform: scale(0.82);
}
35% {
opacity: 1;
}
to {
opacity: 0;
transform: scale(1.18);
}
}
</style>
交錯模式
使用 CSS 自訂屬性以避免重複關鍵幀:
<div class="clip dots" data-start="1" data-duration="3" data-track-index="3">
<span style="--i: 0"></span>
<span style="--i: 1"></span>
<span style="--i: 2"></span>
</div>
<style>
.dots span {
display: inline-block;
width: 18px;
height: 18px;
margin-right: 10px;
border-radius: 50%;
background: currentColor;
animation: dot-pop 900ms ease-out both;
animation-delay: calc(var(--i) * 120ms);
}
@keyframes dot-pop {
from {
opacity: 0;
transform: translateY(18px) scale(0.75);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
</style>
良好用途
- 具有已知重複次數的裝飾性循環。
- 遮罩、光暈、微光、顆粒與細微視差圖層。
- 使用完整 JS 時間線會過度設計的簡單單元素入場。
避免事項
- 無限 CSS 動畫,除非你已確認瀏覽器暴露了可供搜尋的 WAAPI 支援的 CSS 動畫控制句柄。偏好使用涵蓋可見持續時間的有限重複次數。
- 當變形(transforms)可達成時,動畫化佈局屬性,如
top、left、width或height。 - 依賴懸浮(hover)、焦點(focus)、滾動(scroll)或媒體查詢(media queries)來觸發渲染關鍵的運動。
- 在啟動後更改動畫類別,除非另一個確定性時間線控制該更改。
驗證
編輯 CSS 動畫組合後:
npx hyperframes lint
npx hyperframes validate
鳴謝與參考資料
- HyperFrames 適配器原始碼:
packages/core/src/runtime/adapters/css.ts。 - MDN CSS 動畫文件:https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/animation
- MDN
animation-fill-mode:https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode