js实现宝剑
使用JavaScript实现宝剑效果
在JavaScript中实现宝剑效果可以通过Canvas绘图或CSS动画结合交互事件完成。以下是两种常见方法:
Canvas绘制动态宝剑

const canvas = document.getElementById('swordCanvas');
const ctx = canvas.getContext('2d');
function drawSword() {
// 剑柄
ctx.fillStyle = '#8B4513';
ctx.fillRect(100, 50, 20, 100);
// 护手
ctx.fillStyle = '#C0C0C0';
ctx.beginPath();
ctx.moveTo(90, 70);
ctx.lineTo(130, 70);
ctx.lineTo(130, 80);
ctx.lineTo(90, 80);
ctx.closePath();
ctx.fill();
// 剑身
ctx.fillStyle = '#E6E6FA';
ctx.beginPath();
ctx.moveTo(110, 50);
ctx.lineTo(115, 10);
ctx.lineTo(105, 10);
ctx.closePath();
ctx.fill();
}
// 添加鼠标跟随效果
canvas.addEventListener('mousemove', (e) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(e.offsetX, e.offsetY);
drawSword();
ctx.restore();
});
CSS动画宝剑效果
<div class="sword">
<div class="blade"></div>
<div class="hilt"></div>
<div class="guard"></div>
</div>
<style>
.sword {
position: relative;
width: 200px;
height: 400px;
}
.blade {
position: absolute;
width: 20px;
height: 300px;
background: linear-gradient(to right, #ddd, #fff);
border-radius: 5px;
top: 0;
left: 90px;
box-shadow: 0 0 10px rgba(255,255,255,0.8);
animation: glow 2s infinite alternate;
}
@keyframes glow {
from { box-shadow: 0 0 5px #fff; }
to { box-shadow: 0 0 20px #fff; }
}
</style>
实现宝剑物理效果
为宝剑添加碰撞检测和物理特性:

class Sword {
constructor(x, y) {
this.x = x;
this.y = y;
this.angle = 0;
this.length = 150;
}
update(targetX, targetY) {
const dx = targetX - this.x;
const dy = targetY - this.y;
this.angle = Math.atan2(dy, dx);
}
draw(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
// 绘制剑身
ctx.fillStyle = 'silver';
ctx.fillRect(0, -5, this.length, 10);
// 绘制剑柄
ctx.fillStyle = 'brown';
ctx.fillRect(-20, -8, 20, 16);
ctx.restore();
}
}
实现宝剑攻击效果
添加攻击动画和命中检测:
let isAttacking = false;
function attack() {
if(isAttacking) return;
isAttacking = true;
const swordElement = document.querySelector('.sword');
swordElement.style.transition = 'transform 0.2s';
swordElement.style.transform = 'rotate(60deg)';
setTimeout(() => {
swordElement.style.transform = 'rotate(0deg)';
isAttacking = false;
}, 200);
// 检测命中
checkHit();
}
document.addEventListener('keydown', (e) => {
if(e.key === ' ') attack();
});
优化性能的技巧
使用requestAnimationFrame进行动画循环:
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
sword.update(mouseX, mouseY);
sword.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop();
考虑使用WebGL或Three.js实现3D宝剑效果,这对性能要求较高的场景更合适。






