js实现闪电
使用Canvas绘制闪电效果
通过HTML5的Canvas API可以动态生成闪电效果。以下是一个简单的实现方法:

const canvas = document.getElementById('lightningCanvas');
const ctx = canvas.getContext('2d');
function drawLightning() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
const startX = Math.random() * canvas.width;
const startY = 0;
ctx.moveTo(startX, startY);
let currentX = startX;
let currentY = startY;
while (currentY < canvas.height) {
const nextX = currentX + (Math.random() - 0.5) * 30;
const nextY = currentY + Math.random() * 20 + 10;
ctx.lineTo(nextX, nextY);
currentX = nextX;
currentY = nextY;
}
ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
ctx.lineWidth = 2;
ctx.stroke();
// 添加闪光效果
ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
setInterval(drawLightning, 300);
使用CSS动画创建闪电效果
纯CSS也可以模拟闪电效果,适合简单的视觉展示:

<style>
.lightning {
position: absolute;
width: 2px;
height: 100%;
background: white;
left: 50%;
box-shadow: 0 0 10px 2px white;
opacity: 0;
animation: lightning 4s infinite;
}
@keyframes lightning {
0% { opacity: 0; }
1% { opacity: 0.8; }
2% { opacity: 0; }
8% { opacity: 0; }
9% { opacity: 0.5; }
10% { opacity: 0; }
100% { opacity: 0; }
}
</style>
<div class="lightning"></div>
使用Three.js创建3D闪电
对于更复杂的3D场景,可以使用Three.js库:
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();
function createLightning() {
const points = [];
points.push(new THREE.Vector3(0, 10, 0));
for (let i = 1; i < 10; i++) {
points.push(new THREE.Vector3(
points[i-1].x + (Math.random() - 0.5) * 2,
points[i-1].y - Math.random() * 3,
0
));
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({ color: 0x00ffff });
const lightning = new THREE.Line(geometry, material);
scene.add(lightning);
setTimeout(() => scene.remove(lightning), 100);
}
setInterval(createLightning, 1000);
优化闪电效果
为了更真实的闪电效果,可以考虑以下优化:
- 添加分支闪电
- 实现渐变消失效果
- 添加环境光变化
- 使用粒子系统增强视觉效果
每种方法适用于不同场景,Canvas适合2D游戏,CSS适合简单页面效果,Three.js适合3D场景。根据需求选择合适方案。






