canvas

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html,
        body {
            width: 100%;
            height: 100%;
        }
        div {
            width: 100%;
            height: 100%;
            background: #000;
        }
        .home_bg {
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 0;
        }
    </style>
    <body>
        <div>
            <canvas id="canvas-bg"></canvas>
        </div>
        <script>
            const drawBg = () => {
                const canvas = document.getElementById('canvas-bg')
                if (canvas === null) return
                const ctx = canvas?.getContext('2d')
                ctx.canvas.width = window.innerWidth
                ctx.canvas.height = window.innerHeight
                const cW = canvas.width
                const cH = canvas.height
                const stars = []
                // add star with random position
                function addStar() {
                    const x = Math.floor(Math.random() * cW) + -200
                    const y = Math.floor(Math.random() * cH) + 1
                    const s = Math.floor(Math.random() * 12) + 1
                    stars.push({ x: x, y: y, s: s })
                }

                function starField() {
                    addStar()
                    for (let i = 0; i < stars.length; i++) {
                        ctx.fillStyle = 'rgba(255, 255, 255, 1)'
                        ctx.fillRect(stars[i].x++, stars[i].y, stars[i].s * 0.15, stars[i].s * 0.15)
                        ctx.fill()
                        if (stars[i].x > cW) {
                            stars.splice(i, 1)
                        }
                    }
                }
                // animate
                function animate() {
                    ctx.save()
                    ctx.clearRect(0, 0, cW, cH)
                    starField()
                    ctx.restore()
                }
                const animateInterval = setInterval(animate, 50)
            }
            window.onload = () => {
                drawBg()
            }
        </script>
    </body>
</html>

 

posted @ 2024-02-21 16:34  外行的小白  阅读(5)  评论(0编辑  收藏  举报