js实现掉落
实现掉落效果的几种方法
使用CSS动画实现基础掉落
通过CSS的@keyframes和transform属性创建垂直移动动画,适用于简单场景:
.falling-object {
animation: fall 2s linear forwards;
}
@keyframes fall {
to { transform: translateY(100vh); }
}
使用JavaScript控制物理效果
通过requestAnimationFrame实现更真实的物理掉落,包含加速度和反弹效果:
let posY = 0;
let velocity = 0;
const gravity = 0.5;
const element = document.getElementById('ball');
function animate() {
velocity += gravity;
posY += velocity;
if (posY > window.innerHeight - 50) {
posY = window.innerHeight - 50;
velocity *= -0.7; // 反弹系数
}
element.style.top = posY + 'px';
requestAnimationFrame(animate);
}
animate();
使用Canvas实现多物体掉落
在Canvas中批量处理多个掉落物体,适合游戏开发场景:
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const objects = Array(10).fill().map(() => ({
x: Math.random() * canvas.width,
y: 0,
radius: 10 + Math.random() * 20,
speed: 1 + Math.random() * 3
}));
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
objects.forEach(obj => {
obj.y += obj.speed;
if (obj.y > canvas.height) obj.y = 0;
ctx.beginPath();
ctx.arc(obj.x, obj.y, obj.radius, 0, Math.PI * 2);
ctx.fill();
});
requestAnimationFrame(update);
}
update();
使用第三方库实现高级效果
对于复杂物理效果,可以考虑使用现成的物理引擎:
// 使用Matter.js示例
const engine = Matter.Engine.create();
const ball = Matter.Bodies.circle(200, 0, 20);
Matter.Composite.add(engine.world, ball);
Matter.Engine.run(engine);
function render() {
// 这里需要与渲染系统配合
requestAnimationFrame(render);
}
render();
性能优化建议
对于大量掉落物体,建议使用对象池技术回收超出屏幕范围的物体。设置合理的帧率限制(如60FPS),避免不必要的样式计算,对于移动端注意减少重绘区域。
浏览器兼容性处理
使用window.requestAnimationFrame的polyfill保证旧浏览器兼容,CSS动画添加前缀:

window.requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame;






