js小球与边框碰撞反弹
时间: 2023-08-12 16:07:50 浏览: 62
要实现小球与边框碰撞反弹,可以按照以下步骤进行:
1. 定义小球的初始位置、半径、速度和颜色等属性。
2. 使用`requestAnimationFrame`方法创建动画效果,并在每一帧中更新小球的位置。
3. 在每一帧中,判断小球是否与边框相碰撞,可以分别检测小球的上下左右四个方向是否超出边框范围。
4. 如果小球与边框相碰撞,则需要改变小球的速度方向,使小球反弹。
下面是一个简单的示例代码,可以实现小球与边框碰撞反弹的效果:
```js
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 定义小球属性
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 25;
var speedX = 5;
var speedY = 5;
var color = '#0095DD';
// 绘制小球
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
// 更新小球位置
function updateBall() {
x += speedX;
y += speedY;
}
// 检测碰撞并反弹
function checkBoundaries() {
if (x - radius < 0 || x + radius > canvas.width) {
speedX = -speedX;
}
if (y - radius < 0 || y + radius > canvas.height) {
speedY = -speedY;
}
}
// 创建动画效果
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
updateBall();
checkBoundaries();
requestAnimationFrame(animate);
}
animate();
```