js实现小球
实现小球动画的JavaScript方法
创建HTML5 Canvas元素作为画布,设置宽度和高度以适应需求。通过JavaScript获取Canvas的上下文,用于绘制图形。
<canvas id="ballCanvas" width="400" height="400"></canvas>
初始化小球对象,包含位置、速度、半径和颜色等属性。使用Math.random()为小球赋予随机初始位置和速度。

const canvas = document.getElementById('ballCanvas');
const ctx = canvas.getContext('2d');
let ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 20,
dx: 2,
dy: -2,
color: 'red'
};
绘制小球的函数
定义绘制函数,使用arc()方法绘制圆形。设置填充样式并调用fill()方法完成绘制。
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
动画循环与边界检测
使用requestAnimationFrame创建动画循环。在每帧更新小球位置,并检测是否碰到边界以反转速度方向。

function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
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(update);
}
update();
添加鼠标交互功能
通过事件监听实现鼠标控制。mousemove事件更新小球位置,click事件可改变小球颜色。
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
ball.x = e.clientX - rect.left;
ball.y = e.clientY - rect.top;
});
canvas.addEventListener('click', () => {
const colors = ['red', 'blue', 'green', 'yellow', 'purple'];
ball.color = colors[Math.floor(Math.random() * colors.length)];
});
多小球实现方案
创建小球数组存储多个小球实例。修改更新和绘制逻辑以处理多个对象。
let balls = Array(10).fill().map(() => ({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 20 + 10,
dx: (Math.random() - 0.5) * 4,
dy: (Math.random() - 0.5) * 4,
color: `rgb(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255})`
}));
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(ball => {
drawBall(ball);
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(update);
}






