js 写一段小球重力跌落
时间: 2023-04-10 21:04:47 浏览: 67
以下是一段使用 JavaScript 实现小球重力跌落的代码:
```javascript
// 获取画布和上下文
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 定义小球的初始位置、速度和加速度
var x = canvas.width / 2;
var y = canvas.height / 2;
var vx = 0;
var vy = 0;
var ax = 0;
var ay = 0.1;
// 定义小球的半径和颜色
var radius = 20;
var color = "blue";
// 定义绘制小球的函数
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
// 定义更新小球位置的函数
function updateBall() {
// 更新速度和位置
vx += ax;
vy += ay;
x += vx;
y += vy;
// 碰到边界时反弹
if (x + radius > canvas.width || x - radius < 0) {
vx = -vx;
}
if (y + radius > canvas.height || y - radius < 0) {
vy = -vy;
}
}
// 定义动画函数
function animate() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制小球
drawBall();
// 更新小球位置
updateBall();
// 循环调用动画函数
requestAnimationFrame(animate);
}
// 开始动画
animate();
```
希望这段代码能够帮助你实现小球重力跌落的效果。