js实现投篮
实现投篮效果的JavaScript代码
创建一个简单的投篮动画可以通过HTML5 Canvas和JavaScript实现。以下是一个基础示例,模拟篮球从投篮点到篮筐的抛物线运动。
// 获取Canvas元素和上下文
const canvas = document.getElementById('basketballCanvas');
const ctx = canvas.getContext('2d');
// 篮球属性
const ball = {
x: 50,
y: canvas.height - 50,
radius: 15,
color: 'orange',
velocityX: 5,
velocityY: -10,
gravity: 0.2
};
// 篮筐属性
const hoop = {
x: canvas.width - 100,
y: 150,
width: 60,
height: 5
};
// 绘制篮球
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
// 绘制篮筐
function drawHoop() {
ctx.fillStyle = 'red';
ctx.fillRect(hoop.x, hoop.y, hoop.width, hoop.height);
}
// 更新篮球位置
function update() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制篮筐
drawHoop();
// 更新篮球位置
ball.x += ball.velocityX;
ball.y += ball.velocityY;
ball.velocityY += ball.gravity;
// 绘制篮球
drawBall();
// 检测是否碰到篮筐
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) {
alert('投篮成功!');
resetBall();
}
// 检测是否出界
if (ball.y > canvas.height || ball.x > canvas.width) {
resetBall();
}
requestAnimationFrame(update);
}
// 重置篮球位置
function resetBall() {
ball.x = 50;
ball.y = canvas.height - 50;
ball.velocityX = 5;
ball.velocityY = -10;
}
// 开始动画
update();
HTML结构
需要添加以下HTML代码来配合JavaScript运行:
<canvas id="basketballCanvas" width="600" height="400"></canvas>
CSS样式
可以添加基本样式增强视觉效果:
#basketballCanvas {
border: 1px solid black;
background-color: #f0f0f0;
display: block;
margin: 0 auto;
}
增强交互性
可以添加鼠标点击事件来控制投篮时机:
canvas.addEventListener('click', function() {
resetBall();
update();
});
物理参数调整
抛物线运动效果可以通过调整以下参数实现不同投篮效果:

velocityX:控制水平速度velocityY:控制初始垂直速度gravity:控制重力影响程度
这些代码创建了一个简单的投篮模拟,篮球会沿着抛物线轨迹运动,当碰到篮筐时会显示成功提示。可以根据需要调整参数来改变投篮的力度和角度。






