js 实现抛物线
实现抛物线的基本原理
在JavaScript中实现抛物线效果,通常基于物理学的抛物线运动公式。抛物线运动由水平匀速运动和垂直匀加速运动合成。核心公式如下:

- 水平位移公式:
( x = v_x \cdot t ) - 垂直位移公式:
( y = v_y \cdot t + \frac{1}{2} g \cdot t^2 )
其中 ( v_x ) 和 ( v_y ) 是初始速度分量,( g ) 是重力加速度,( t ) 是时间。
使用CSS动画实现
通过CSS的animation和@keyframes实现简单抛物线动画,适合不需要动态计算的场景:

@keyframes parabola {
0% { transform: translate(0, 0); }
50% { transform: translate(100px, -100px); }
100% { transform: translate(200px, 0); }
}
.ball {
animation: parabola 2s ease-in-out;
}
使用JavaScript动态计算
通过requestAnimationFrame逐帧更新元素位置,适合需要动态控制参数的场景:
function parabolicAnimation(element, vx, vy, duration) {
const startTime = performance.now();
const g = 0.2; // 重力加速度
function updatePosition(timestamp) {
const elapsed = timestamp - startTime;
if (elapsed > duration) return;
const t = elapsed / 1000; // 转换为秒
const x = vx * t;
const y = vy * t + 0.5 * g * t * t;
element.style.transform = `translate(${x}px, ${y}px)`;
requestAnimationFrame(updatePosition);
}
requestAnimationFrame(updatePosition);
}
// 调用示例
const ball = document.getElementById('ball');
parabolicAnimation(ball, 100, -50, 2000);
贝塞尔曲线模拟
通过三次贝塞尔曲线模拟抛物线路径,适合需要平滑曲线的场景:
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M0,0 Q100,-100 200,0');
const ball = document.getElementById('ball');
const length = path.getTotalLength();
function animateAlongPath() {
let distance = 0;
const duration = 2000;
function updatePosition(timestamp) {
distance = (timestamp % duration) / duration * length;
const point = path.getPointAtLength(distance);
ball.style.transform = `translate(${point.x}px, ${point.y}px)`;
requestAnimationFrame(updatePosition);
}
requestAnimationFrame(updatePosition);
}
animateAlongPath();
注意事项
- 重力加速度(
g)的值需根据实际效果调整,通常通过实验确定。 - 使用
transform进行位移优化性能,避免直接修改left/top。 - 在动画结束后调用
cancelAnimationFrame避免内存泄漏。






