下面是一个使用 JavaScript 和 HTML5 Canvas 实现的动态流星雨效果。这个效果可以在网页上创建一个黑色背景,并在画布上绘制多个流星从右上角斜向左下角移动,模拟流星雨的视觉效果。
✅ 实现步骤:
- 创建一个
<canvas>
元素。 - 使用 JavaScript 在 Canvas 上绘制和动画流星。
- 每颗流星有随机的起始位置、速度、长度和亮度。
- 流星移动并逐渐淡出,模拟拖尾效果。
✅ 完整代码:
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8" /><title>流星雨效果</title><style>body {margin: 0;overflow: hidden;background: #000;}canvas {display: block;}</style>
</head>
<body><canvas id="starCanvas"></canvas><script>const canvas = document.getElementById('starCanvas');const ctx = canvas.getContext('2d');// 设置画布大小为窗口大小canvas.width = window.innerWidth;canvas.height = window.innerHeight;// 流星数组const meteors = [];const meteorCount = 15; // 流星数量// 流星构造函数function Meteor() {this.reset();}Meteor.prototype.reset = function() {// 随机从右侧上方出现this.x = canvas.width + 20;this.y = Math.random() * canvas.height * 0.5; // 只在上半部分出现this.vx = -(5 + Math.random() * 5); // 向左移动this.vy = 2 + Math.random() * 3; // 向下移动this.length = 30 + Math.random() * 50;this.opacity = 0.8 + Math.random() * 0.2;this.fade = 0.02 + Math.random() * 0.03; // 淡出速度this.width = 1 + Math.random() * 2;};Meteor.prototype.update = function() {this.x += this.vx;this.y += this.vy;this.opacity -= this.fade;// 如果流星淡出或移出屏幕,重置if (this.opacity <= 0 || this.x < -this.length || this.y > canvas.height) {this.reset();}};Meteor.prototype.draw = function() {ctx.save();ctx.globalAlpha = this.opacity;ctx.strokeStyle = '#fff';ctx.lineWidth = this.width;ctx.beginPath();ctx.moveTo(this.x, this.y);// 画流星的拖尾ctx.lineTo(this.x - this.length, this.y + this.length * 0.8);ctx.stroke();ctx.restore();};// 初始化流星for (let i = 0; i < meteorCount; i++) {meteors.push(new Meteor());}// 动画循环function animate() {// 清除画布(保留一点残影可注释掉)ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';ctx.fillRect(0, 0, canvas.width, canvas.height);// 更新并绘制每个流星meteors.forEach(meteor => {meteor.update();meteor.draw();});requestAnimationFrame(animate);}// 开始动画animate();// 窗口大小改变时重置画布window.addEventListener('resize', () => {canvas.width = window.innerWidth;canvas.height = window.innerHeight;});</script>
</body>
</html>
✅ 效果说明:
- 黑色背景:模拟夜空。
- 白色斜线:代表流星,带有拖尾。
- 随机参数:每颗流星的速度、长度、透明度都不同,更自然。
- 淡出效果:流星逐渐消失,增强真实感。
- 自动重置:流星离开屏幕后重新生成。
✅ 可扩展功能(可选):
- 添加星星背景(静态小点)。
- 加入音效。
- 点击屏幕生成更多流星。
- 使用
hsl()
颜色实现彩色流星。
把这个代码保存为 .html
文件,用浏览器打开即可看到动态流星雨效果 🌠