js 实现抛物线
在JavaScript中实现抛物线动画效果可以通过数学公式结合CSS或Canvas绘制来实现。以下是两种常见的方法:

使用CSS和JavaScript实现抛物线动画
抛物线的基本公式为 y = a * x^2 + b * x + c,其中a控制开口方向和大小,b和c为偏移量。

// 创建抛物线动画元素
const ball = document.createElement('div');
ball.style.width = '20px';
ball.style.height = '20px';
ball.style.backgroundColor = 'red';
ball.style.borderRadius = '50%';
ball.style.position = 'absolute';
document.body.appendChild(ball);
// 抛物线参数
const a = 0.01; // 控制抛物线开口
const b = 0; // 线性系数
const c = 0; // 常数项
// 动画函数
function animate() {
let x = 0;
const interval = setInterval(() => {
x += 5;
const y = a * Math.pow(x, 2) + b * x + c;
ball.style.left = `${x}px`;
ball.style.top = `${y}px`;
if (x > 300) clearInterval(interval); // 停止条件
}, 30);
}
animate();
使用Canvas绘制抛物线
Canvas更适合复杂的动态绘制,可以实时更新抛物线轨迹。
const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
// 抛物线参数
const a = 0.01;
const b = 0;
const c = 0;
// 绘制抛物线轨迹
function drawParabola() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for (let x = 0; x <= 300; x += 5) {
const y = a * Math.pow(x, 2) + b * x + c;
ctx.lineTo(x, y);
}
ctx.strokeStyle = 'blue';
ctx.stroke();
// 绘制动点
const currentX = (Date.now() / 50) % 300;
const currentY = a * Math.pow(currentX, 2) + b * currentX + c;
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(currentX, currentY, 5, 0, Math.PI * 2);
ctx.fill();
requestAnimationFrame(drawParabola);
}
drawParabola();
实现带初速度的抛物线
若需模拟物理效果(如抛体运动),需考虑水平初速度vx和垂直初速度vy,并加入重力加速度g。
// 物理参数
let x = 0, y = 0;
const vx = 3, vy = -15; // 初速度
const g = 0.2; // 重力加速度
function physicsAnimation() {
x += vx;
y += vy;
vy += g; // 垂直速度受重力影响
ball.style.left = `${x}px`;
ball.style.top = `${y}px`;
if (x < 300) requestAnimationFrame(physicsAnimation);
}
physicsAnimation();
注意事项
- CSS方法适合简单DOM元素动画,性能较轻。
- Canvas适合复杂绘制,但需手动管理渲染。
- 物理模拟中,
g和初速度需根据实际需求调整。 - 使用
requestAnimationFrame比setInterval更流畅。
以上方法可根据具体场景选择或组合使用。






