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 動畫控制代碼。優先使用涵蓋可見持續時間的有限迭代次數。
- 在可以使用 transform 時,動畫化佈局屬性,例如
top、left、width或height。 - 依賴懸停、焦點、滾動或媒體查詢來觸發渲染關鍵的運動。
- 在啟動後更改動畫類別,除非另一個確定性時間軸控制該更改。
驗證
在編輯 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