css动画如何实现抛物线效果_css动画复杂轨迹思路

9次阅读

css无法精确实现抛物线动画,因其@keyframes仅支持线性、缓动或分段关键帧,无法描述二次函数轨迹;推荐js计算坐标+CSS硬件加速方案,或用两段cubic-bezier近似模拟。

css动画如何实现抛物线效果_css动画复杂轨迹思路

transform + @keyframes 模拟抛物线不现实

纯 CSS 的 @keyframes 只支持线性、缓动(cubic-bezier)或分段关键帧,无法直接描述二次函数轨迹(如 y = ax² + bx + c)。强行用 20+ 个 top/left 关键帧逼近,不仅代码臃肿,还难以控制起止速度和物理感,且响应式下会错位。

推荐方案:CSS 配合 JS 控制 transform: translate()

让 JS 计算每个时间点的 xy 坐标,再通过 element.style.transform = `translate(${x}px, ${y}px)` 实时更新。CSS 负责硬件加速(需开启 will-change: transformtransform: translateZ(0)),JS 负责数学逻辑。

  • 抛物线公式建议用参数式:x = v₀ₓ × ty = v₀ᵧ × t − 0.5 × g × t²(更贴近真实投掷)
  • 时间 trequestanimationFrame 控制,避免 setInterval 掉帧
  • 初始速度 v₀ₓ/v₀ᵧ 和重力 g 可调,比硬编码像素值更灵活
  • 务必在动画开始前设置 element.style.transformOrigin = '0 0',避免旋转类干扰
const ball = document.querySelector('.ball'); const duration = 1200; // ms const g = 0.002; const v0x = 2; const v0y = -3; 

let startTime = null; function animate(currentTime) { if (!startTime) startTime = currentTime; const t = currentTime - startTime; if (t > duration) { ball.style.transform = translate(${v0x * duration}px, ${v0y * duration - 0.5 * g * duration ** 2}px); return; } const x = v0x t; const y = v0y t - 0.5 g t * t; ball.style.transform = translate(${x}px, ${y}px); requestAnimationFrame(animate); } requestAnimationFrame(animate);

如果必须纯 CSS:用 cubic-bezier 近似上升+减速+下坠

虽然不是数学意义的抛物线,但人眼对「先快后慢上升、再加速下落」有强感知。可用两个贝塞尔曲线拼接:前半段用 cubic-bezier(0.3, 1.2, 0.5, 1)(模拟上抛减速),后半段用 cubic-bezier(0.5, 0, 0.7, -0.2)(模拟下落加速)。注意:负的 y 值在贝塞尔中合法,但需确保容器 overflow: visible,否则裁剪。

  • 不能只靠一个 cubic-bezier 覆盖全程——它只能表达单调变化,无法同时表现上升减速与下降加速
  • 必须拆成两段动画,用 animation-fill-mode: forwards 衔接,且第二段 animation-delay 设为第一段时间
  • toptransform 都可,但后者性能更好;若用 top,父容器需设 position: relative

容易被忽略的细节:坐标系方向与单位一致性

CSS 的 y 轴向下为正,而物理抛物线公式通常设向上为正。直接套用会导致球往天上飞。要么把公式里的 y 结果取负,要么把重力 g 设为正值并写成 y = -v₀ᵧ × t + 0.5 × g × t²。另外,JS 算出的像素值别直接拼进 transform 字符串——漏写 px 会静默失败;CSS 自定义属性(--x, --y)配合 calc() 是更健壮的传值方式,但兼容性需查 transform: translate(var(--x), var(--y)) 是否被支持。

立即学习前端免费学习笔记(深入)”;

text=ZqhQzanResources