1. 首页
  2. 人工智能
  3. 论文/代码
  4. HTML实现圣诞下雪效果的方法

HTML实现圣诞下雪效果的方法

上传者: 2023-03-10 20:19:03上传 TXT文件 31.48KB 热度 10次

直接创建一个HTML文件,复制进去下面的代码即可实现圣诞下雪效果:

html>

<html>
<head>
    <meta charset="utf-8"/>
    <title>HTML实现圣诞下雪效果的方法title>
    <style>
        #snowContainer {
            position: relative;
            width: 100%;
            height: 100vh;
            background: url(snow.jpg);
            background-size: cover;
        }
        #snowCanvas {
            position: absolute;
            top: 0;
            left: 0;
        }
    style>
head>
<body>
<div id="snowContainer">div>
<script>
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        w = canvas.width = window.innerWidth,
        h = canvas.height = window.innerHeight,
        snowflakeCount = 400,
        snowflakes = [];

    function Snowflake() {
        this.x = Math.random() * w;
        this.y = Math.random() * h - h;
        this.ttl = Math.random() * 100 + 100;
        this.speed = Math.random() * 2;
        this.velY = this.speed;
        this.velX = 0;
        this.size = 5;
        this.alpha = 0.5 + Math.random() * 0.5;
    }

    Snowflake.prototype.update = function () {
        this.y += this.velY;
        this.x += this.velX;

        if (this.y >= h) {
            this.reset();
        }

        this.velX *= 0.98;

        if (this.ttl < 0) {
            this.reset();
        }

        this.ttl--;
    };

    Snowflake.prototype.reset = function () {
        this.y = Math.random() * h - h;
        this.x = Math.random() * w;
        this.ttl = Math.random() * 100 + 100;
        this.speed = Math.random() * 2;
        this.velY = this.speed;
        this.velX = 0;
        this.size = 5;
        this.alpha = 0.5 + Math.random() * 0.5;
    };

    function init() {
        for (var i = 0; i < snowflakeCount; i++) {
            snowflakes.push(new Snowflake());
        }
        loop();
    }

    function loop() {
        requestAnimationFrame(loop);
        ctx.clearRect(0, 0, w, h);

        for (var i = 0; i < snowflakeCount; i++) {
            var flake = snowflakes[i];
            flake.update();
            ctx.beginPath();
            ctx.arc(flake.x, flake.y, flake.size, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(255, 255, 255, ' + flake.alpha + ')';
            ctx.fill();
        }
    }

    canvas.setAttribute('id', 'snowCanvas');
    document.getElementById('snowContainer').appendChild(canvas);
    window.addEventListener('resize', function () {
        w = canvas.width = window.innerWidth;
        h = canvas.height = window.innerHeight;
    });

    init();
script>
body>
html>
用户评论