js实现投篮
JavaScript 实现投篮动画
使用 HTML5 Canvas 和 JavaScript 可以创建一个简单的投篮动画。以下是一个基础实现示例,模拟篮球的抛物线运动及篮筐碰撞检测。

初始化 Canvas 和基本参数
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let ball = { x: 50, y: 300, radius: 15, vx: 5, vy: -10 };
const hoop = { x: 400, y: 150, width: 60, height: 5 };
let gravity = 0.2;
let isShooting = false;
绘制篮球和篮筐
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = 'orange';
ctx.fill();
ctx.stroke();
}
function drawHoop() {
ctx.fillStyle = 'black';
ctx.fillRect(hoop.x, hoop.y, hoop.width, hoop.height);
}
更新篮球位置(抛物线运动)
function updateBall() {
ball.vy += gravity; // 重力加速度
ball.x += ball.vx;
ball.y += ball.vy;
// 碰撞检测:篮筐
if (
ball.x + ball.radius > hoop.x &&
ball.x - ball.radius < hoop.x + hoop.width &&
ball.y + ball.radius > hoop.y &&
ball.y - ball.radius < hoop.y + hoop.height
) {
ball.vy *= -0.6; // 反弹
ball.vx *= 0.9; // 摩擦力
}
// 边界检测
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= -0.5; // 地面反弹
}
}
动画循环
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawHoop();
drawBall();
if (isShooting) updateBall();
requestAnimationFrame(gameLoop);
}
gameLoop();
触发投篮
document.addEventListener('click', () => {
isShooting = true;
ball = { x: 50, y: 300, radius: 15, vx: 5, vy: -10 }; // 重置初始速度
});
HTML 结构
<canvas id="gameCanvas" width="500" height="400"></canvas>
增强功能建议
-
调整投篮力度:通过鼠标拖动距离计算初始速度。

let startPos = null; canvas.addEventListener('mousedown', (e) => { startPos = { x: e.clientX, y: e.clientY }; }); canvas.addEventListener('mouseup', (e) => { if (startPos) { const dx = e.clientX - startPos.x; const dy = e.clientY - startPos.y; ball.vx = dx * 0.1; ball.vy = dy * 0.1; isShooting = true; } }); -
添加篮球纹理:在
drawBall()中使用drawImage加载篮球图片替代简单圆形。 -
得分系统:检测篮球穿过篮筐中心时增加分数。
完整代码可参考 CodePen 示例。






