用html实现小球与边框碰撞反弹
时间: 2024-02-21 09:59:21 浏览: 83
可以使用HTML5的Canvas和JavaScript实现小球与边框碰撞反弹的效果。以下是一个简单的实现:
首先,在HTML中创建一个Canvas元素和一个JavaScript脚本:
```html
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script src="script.js"></script>
</body>
</html>
```
然后,在JavaScript中编写代码,实现小球的绘制、移动和碰撞反弹:
```javascript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 小球的初始位置和速度
var x = canvas.width / 2;
var y = canvas.height / 2;
var dx = 2;
var dy = -2;
var ballRadius = 10;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
// 每次移动前清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制小球
drawBall();
// 如果小球碰到边缘,反弹
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
// 更新小球的位置
x += dx;
y += dy;
}
setInterval(draw, 10);
```
这段代码中,首先获取Canvas元素和绘图上下文对象。然后定义小球的初始位置和速度,并编写绘制小球和移动小球的函数。在draw函数中,每次先清除画布,然后绘制小球并判断是否碰到边缘,如果碰到边缘则反弹并更新小球的位置。最后使用setInterval函数让draw函数每隔一段时间执行一次,从而实现小球的动画效果。
这样,就可以实现小球与边框的碰撞反弹效果了。
阅读全文
相关推荐















