js实现射箭
使用 Canvas 实现射箭动画
在 JavaScript 中实现射箭效果可以通过 HTML5 的 Canvas 结合动画原理来完成。以下是一个基础的实现方法:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let arrow = {
x: 50,
y: canvas.height / 2,
speed: 0,
angle: 0,
flying: false
};
function drawArrow() {
ctx.save();
ctx.translate(arrow.x, arrow.y);
ctx.rotate(arrow.angle);
// 绘制箭杆
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(30, 0);
ctx.strokeStyle = 'brown';
ctx.lineWidth = 2;
ctx.stroke();
// 绘制箭头
ctx.beginPath();
ctx.moveTo(30, 0);
ctx.lineTo(25, -5);
ctx.lineTo(25, 5);
ctx.closePath();
ctx.fillStyle = 'gray';
ctx.fill();
ctx.restore();
}
function update() {
if (arrow.flying) {
arrow.x += arrow.speed * Math.cos(arrow.angle);
arrow.y += arrow.speed * Math.sin(arrow.angle);
arrow.speed *= 0.98; // 空气阻力
// 边界检测
if (arrow.x > canvas.width || arrow.y < 0 || arrow.y > canvas.height) {
resetArrow();
}
}
}
function resetArrow() {
arrow.x = 50;
arrow.y = canvas.height / 2;
arrow.speed = 0;
arrow.flying = false;
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
update();
drawArrow();
requestAnimationFrame(animate);
}
// 发射箭
canvas.addEventListener('click', () => {
if (!arrow.flying) {
arrow.speed = 10;
arrow.flying = true;
}
});
animate();
添加物理效果增强真实感
为了增加真实感,可以引入重力加速度和更精确的物理计算:

const gravity = 0.2;
function update() {
if (arrow.flying) {
arrow.x += arrow.speed * Math.cos(arrow.angle);
arrow.y += arrow.speed * Math.sin(arrow.angle);
arrow.speed *= 0.98;
arrow.y += gravity; // 重力影响
if (arrow.x > canvas.width || arrow.y < 0 || arrow.y > canvas.height) {
resetArrow();
}
}
}
添加瞄准功能
允许用户调整箭的发射角度:
let mouseX = 0, mouseY = 0;
canvas.addEventListener('mousemove', (e) => {
if (!arrow.flying) {
mouseX = e.clientX - canvas.offsetLeft;
mouseY = e.clientY - canvas.offsetTop;
arrow.angle = Math.atan2(mouseY - arrow.y, mouseX - arrow.x);
}
});
添加目标物体
在场景中添加目标可以增加交互性:
const target = {
x: canvas.width - 100,
y: canvas.height / 2,
radius: 20
};
function drawTarget() {
ctx.beginPath();
ctx.arc(target.x, target.y, target.radius, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
}
function checkHit() {
const dx = arrow.x - target.x;
const dy = arrow.y - target.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < target.radius) {
alert('命中目标!');
resetArrow();
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
update();
drawTarget();
drawArrow();
if (arrow.flying) checkHit();
requestAnimationFrame(animate);
}
完整HTML结构
<!DOCTYPE html>
<html>
<head>
<title>射箭游戏</title>
<style>
#gameCanvas {
border: 1px solid black;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="400"></canvas>
<script>
// 上述JavaScript代码放在这里
</script>
</body>
</html>
这个实现提供了基本的射箭功能,包括箭的绘制、物理运动、瞄准和目标检测。可以根据需要进一步扩展,如添加多个目标、计分系统或更复杂的物理效果。






