当前位置:首页 > JavaScript

js实现星空

2026-03-14 11:46:43JavaScript

实现星空效果的JavaScript代码

以下是一个使用HTML5 Canvas和JavaScript创建星空动画效果的示例代码。该代码会生成随机分布的星星,并模拟闪烁和移动效果。

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript星空效果</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: #000;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="starfield"></canvas>
    <script>
        const canvas = document.getElementById('starfield');
        const ctx = canvas.getContext('2d');

        // 设置画布大小为窗口大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        // 星星数组
        const stars = [];
        const starCount = 500; // 星星数量

        // 星星类
        class Star {
            constructor() {
                this.x = Math.random() * canvas.width;
                this.y = Math.random() * canvas.height;
                this.size = Math.random() * 1.5;
                this.speed = Math.random() * 0.2;
                this.opacity = Math.random();
                this.opacityChange = Math.random() * 0.02;
            }

            update() {
                this.y += this.speed;
                this.opacity += this.opacityChange;

                // 如果星星移出屏幕底部,重置到顶部
                if (this.y > canvas.height) {
                    this.y = 0;
                    this.x = Math.random() * canvas.width;
                }

                // 反转透明度变化方向
                if (this.opacity > 1 || this.opacity < 0) {
                    this.opacityChange = -this.opacityChange;
                }
            }

            draw() {
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
                ctx.fill();
            }
        }

        // 初始化星星
        for (let i = 0; i < starCount; i++) {
            stars.push(new Star());
        }

        // 动画循环
        function animate() {
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            for (const star of stars) {
                star.update();
                star.draw();
            }

            requestAnimationFrame(animate);
        }

        // 窗口大小改变时重置画布
        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });

        animate();
    </script>
</body>
</html>

代码说明

  1. Canvas设置

    • 创建全屏Canvas元素
    • 获取2D渲染上下文
    • 监听窗口大小变化并调整Canvas尺寸
  2. 星星类(Star)

    • 随机生成星星的初始位置(x,y)
    • 随机设置星星大小、速度和初始透明度
    • 实现星星下落和透明度变化动画
  3. 动画循环

    js实现星空

    • 使用半透明黑色矩形覆盖实现拖尾效果
    • 更新并绘制所有星星
    • 使用requestAnimationFrame实现平滑动画

自定义选项

可以通过修改以下参数来自定义星空效果:

// 星星数量(默认500)
const starCount = 800;

// 星星最大尺寸(默认1.5)
this.size = Math.random() * 3;

// 星星下落速度(默认0.2)
this.speed = Math.random() * 0.5;

// 透明度变化速度(默认0.02)
this.opacityChange = Math.random() * 0.05;

进阶优化

  1. 添加流星效果 可以扩展代码,随机生成从屏幕一侧飞向另一侧的流星。

    js实现星空

  2. 不同颜色的星星 修改fillStyle,使用HSL颜色空间实现多彩星空:

    ctx.fillStyle = `hsla(${Math.random()*360}, 100%, 50%, ${this.opacity})`;
  3. 视差效果 创建不同速度的多层星星,模拟深度感。

  4. 交互效果 监听鼠标移动事件,使星星产生避让效果。

标签: 星空js
分享给朋友:

相关文章

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…