当前位置:首页 > JavaScript

js 实现抛物线

2026-03-01 20:14:17JavaScript

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

js 实现抛物线

使用CSS和JavaScript实现抛物线动画

抛物线的基本公式为 y = a * x^2 + b * x + c,其中a控制开口方向和大小,bc为偏移量。

js 实现抛物线

// 创建抛物线动画元素
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和初速度需根据实际需求调整。
  • 使用requestAnimationFramesetInterval更流畅。

以上方法可根据具体场景选择或组合使用。

标签: 抛物线js
分享给朋友:

相关文章

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 // 获取所有…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现求导

js实现求导

实现数值求导的方法 在JavaScript中实现求导通常采用数值方法,因为JavaScript不是符号计算语言。以下是常见的数值微分方法: 中心差分法 中心差分法提供较高精度的导数近似:…