js实现小球
实现小球动画的 JavaScript 方法
使用 Canvas 绘制小球
创建一个 Canvas 元素并设置其宽高,通过 JavaScript 获取上下文进行绘制:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 20,
dx: 2,
dy: -2,
color: 'red'
};
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
实现小球运动逻辑
更新小球位置并处理边界碰撞检测:
function updateBall() {
ball.x += ball.dx;
ball.y += ball.dy;
// 左右边界碰撞
if (ball.x + ball.dx > canvas.width - ball.radius || ball.x + ball.dx < ball.radius) {
ball.dx = -ball.dx;
}
// 上下边界碰撞
if (ball.y + ball.dy > canvas.height - ball.radius || ball.y + ball.dy < ball.radius) {
ball.dy = -ball.dy;
}
}
动画循环

使用 requestAnimationFrame 实现平滑动画:
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
updateBall();
requestAnimationFrame(animate);
}
animate();
使用 CSS 实现小球效果
HTML 结构
<div class="ball"></div>
CSS 样式

.ball {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: blue;
position: absolute;
}
JavaScript 控制动画
const ball = document.querySelector('.ball');
let x = 0, y = 0;
let dx = 2, dy = 2;
function moveBall() {
x += dx;
y += dy;
// 边界检测
if (x + 50 > window.innerWidth || x < 0) dx = -dx;
if (y + 50 > window.innerHeight || y < 0) dy = -dy;
ball.style.transform = `translate(${x}px, ${y}px)`;
requestAnimationFrame(moveBall);
}
moveBall();
物理效果增强
添加重力加速度
let gravity = 0.2;
let friction = 0.99;
function applyPhysics() {
ball.dy += gravity;
ball.dx *= friction;
ball.dy *= friction;
ball.y += ball.dy;
ball.x += ball.dx;
// 地面碰撞
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.dy = -ball.dy * 0.8; // 弹性系数
}
}
交互控制示例
鼠标点击生成小球
canvas.addEventListener('click', (e) => {
const newBall = {
x: e.clientX,
y: e.clientY,
radius: Math.random() * 20 + 10,
dx: (Math.random() - 0.5) * 4,
dy: (Math.random() - 0.5) * 4,
color: `hsl(${Math.random() * 360}, 100%, 50%)`
};
balls.push(newBall);
});
完整示例整合 将上述代码片段组合即可创建交互式小球动画系统,支持多球物理模拟和用户交互。






