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.fillRect(90, 70, 40, 10);
// 剑身
ctx.fillStyle = '#E6E6FA';
ctx.beginPath();
ctx.moveTo(110, 50);
ctx.lineTo(130, 10);
ctx.lineTo(90, 10);
ctx.closePath();
ctx.fill();
// 剑光效果
ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(110, 10);
ctx.lineTo(110, 0);
ctx.stroke();
}
drawSword();
CSS动画方法

<div class="sword">
<div class="hilt"></div>
<div class="guard"></div>
<div class="blade"></div>
<div class="glow"></div>
</div>
<style>
.sword {
position: relative;
width: 200px;
height: 300px;
}
.hilt {
position: absolute;
width: 20px;
height: 100px;
background: #8B4513;
left: 100px;
top: 50px;
}
.guard {
position: absolute;
width: 40px;
height: 10px;
background: #C0C0C0;
left: 90px;
top: 70px;
}
.blade {
position: absolute;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-bottom: 40px solid #E6E6FA;
left: 90px;
top: 10px;
}
.glow {
position: absolute;
width: 2px;
height: 10px;
background: rgba(255, 255, 255, 0.7);
left: 109px;
top: 0;
animation: pulse 1s infinite alternate;
}
@keyframes pulse {
from { opacity: 0.5; }
to { opacity: 1; }
}
</style>
添加交互功能
可以为宝剑添加鼠标跟随或点击动画效果:
document.addEventListener('mousemove', (e) => {
const sword = document.querySelector('.sword');
const angle = Math.atan2(e.clientY - 150, e.clientX - 100);
sword.style.transform = `rotate(${angle}rad)`;
});
document.addEventListener('click', () => {
const blade = document.querySelector('.blade');
blade.style.transform = 'scale(1.2)';
setTimeout(() => {
blade.style.transform = 'scale(1)';
}, 300);
});
3D宝剑效果
使用Three.js创建3D宝剑:
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建剑的各个部分
const hiltGeometry = new THREE.BoxGeometry(0.2, 1, 0.2);
const hiltMaterial = new THREE.MeshBasicMaterial({color: 0x8B4513});
const hilt = new THREE.Mesh(hiltGeometry, hiltMaterial);
scene.add(hilt);
const bladeGeometry = new THREE.ConeGeometry(0.15, 2, 4);
const bladeMaterial = new THREE.MeshBasicMaterial({color: 0xE6E6FA});
const blade = new THREE.Mesh(bladeGeometry, bladeMaterial);
blade.position.y = 1.5;
scene.add(blade);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
blade.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
这些方法可以根据需求进行组合和扩展,创建出更复杂的宝剑效果。






