JavaScript实现雪花效果代码
首页 学习分享 精品应用 资源收藏 心情随笔 关于我们 登录
JavaScript实现雪花效果代码

本文最后更新于2月前,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

您阅读本篇文章共花了: 

代码如下:

<canvas id="snow"  width="1210" height="600"></canvas>
<script>
    function snow(id='snow', opacity=0.8, backgroundColor='rgba(0, 0, 0, 1)') {
        var canvas = document.getElementById(id);
        if (!canvas) return;
        var ctx = canvas.getContext('2d');

        function Flake() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.radius = Math.random() * 3 + 1;
            this.speedY = Math.random() * 1 + 0.5;
            this.speedX = Math.random() * 2 - 1;
            this.opacity = Math.random() * (0.8 - 0.2) + 0.2;

            this.update = function() {
                this.y += this.speedY;
                if (this.y > canvas.height) {
                    this.y = -this.radius;
                    this.x = Math.random() * canvas.width;
                }
                this.x += this.speedX;
                if (this.x > canvas.width || this.x < 0) {
                    this.x = Math.random() * canvas.width;
                }
            };

            this.draw = function() {
                ctx.fillStyle = 'rgba(255, 255, 255, ' + (this.opacity * opacity) + ')';
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
                ctx.fill();
                ctx.closePath();
            };
        }

        var flakes = [];
        for (var i = 0; i < 200; i++) {
            flakes.push(new Flake());
        }

        function animate() {
            // 设置背景颜色
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            flakes.forEach(function(flake) {
                flake.update();
                flake.draw();
            });
            requestAnimationFrame(animate);
        }

        animate();
    }

    document.addEventListener('DOMContentLoaded', function(){
        snow(undefined, 0.8, 'rgba(0, 0, 0, 1)'); // 全局透明度调节值和背景颜色
    });
</script>

演示效果如下:

上一篇:JavaScript实现下雨效果代码
下一篇:佛法之苦谛,细谈人生有八苦
验证码
评论留言 (0条)