在JavaScript中实现一个随机运动的小球,通常涉及到HTML5的Canvas绘图和JavaScript的动画逻辑。以下是一个简单的示例,展示了如何创建一个小球,并使其在画布上随机移动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Moving Ball</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script src="script.js"></script>
</body>
</html>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
class Ball {
constructor(x, y, radius, dx, dy) {
this.x = x;
this.y = y;
this.radius = radius;
this.dx = dx;
this.dy = dy;
this.color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const ball = new Ball(
canvas.width / 2,
canvas.height / 2,
20,
getRandomInt(-5, 5),
getRandomInt(-5, 5)
);
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.update();
}
animate();
canvas
元素,用于绘制小球。Ball
类:定义小球的属性(位置、半径、速度、颜色)和方法(绘制和更新位置)。getRandomInt
函数:生成一个指定范围内的随机整数。Ball
实例,初始位置在画布中心,速度为随机值。animate
函数:使用requestAnimationFrame
实现动画循环,每次循环清除画布并更新小球的位置。getRandomInt
函数的参数来控制速度范围。requestAnimationFrame
和批量绘制优化性能。这个示例展示了如何使用JavaScript和Canvas创建一个简单的随机运动小球,并解释了相关的基础概念和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云