HTML+JS front-end snowflakes falling

1 Overview:

Use any picture as the background, and add the special effect of falling snowflakes on the background, which is realized here by using random-sized colored snowflakes.

2. Realize the function:

(1) Snowflakes appear randomly and disappear randomly;

(2) The size of the snowflakes appears randomly;

(3) The color of the snowflake gradually fades and disappears;

(4) After the snowflake disappears, its object is deleted to reduce the burden on the system.

3. Complete implementation code:

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: black;
        }
    </style>
</head>

<body>
    <script src="雪花.js"></script>
</body>

</html>

JS: 

function flake() {
    //先写静态再写动态
    //一朵雪花在屏幕内随即摆放
    var f = document.createElement("img");
    f.src = "flake.png";
    //随机问题用随机函数
    //先获取屏幕的宽高,在用随机函数得到一个随机的X Y值
    var width = document.documentElement.clientWidth;
    var heigh = document.documentElement.clientHeight;
    //获取屏幕随机坐标
    var left = Math.random() * width;
    var top = Math.random() * heigh;
    //  alert(width)
    f.style.position = "absolute";
    f.style.left = left + "px";
    f.style.top = top + "px";
    //随即缩放
    f.style.transform = "scale(" + Math.random() / 2 + ")"
    //将这个标签插入到body中
    document.body.appendChild(f);
    //在JS中可以使用方法里面的方法
    function down() {
        top++;
        left++;
        f.style.left = left + "px";
        f.style.top = top + "px";
        if (top > heigh) {
            top = -100;
        }
        if (left > width) {
            left = -100;
        }
    }
    setInterval(down, 20)
}
//下落
function down() {
    f.style.top++
}
setInterval(down, 1000)
for (var i = 0; i < 50; i++) {
    flake()
}

4. Realize the effect

Guess you like

Origin blog.csdn.net/Jhoonyp/article/details/122468468