Home > Web Front-end > HTML Tutorial > How to achieve snow effect in html5

How to achieve snow effect in html5

一个新手
Release: 2018-05-17 16:14:23
Original
8829 people have browsed it

Use canvas to achieve a snowing effect. Let’s preview the effect first:

Let’s analyze this effect first:

1, randomly generate snowflakes

2 , the snowflakes are not produced at the same time, but in sequence

3, how to express snowflakes

4, how to snow continuously

5, how big are snowflakes? After a little

figured out the above issues, this effect was basically realized.

First of all, since this is a full-screen effect, I used dynamically created canvas to display the entire browsing Assign the width and height of the browser to canvas

var Canvas = function (w, h) {
                this.width = w;
                this.height = h;
            }
            Canvas.prototype = {
                init: function () {
                    var oC = document.createElement("canvas");
                    oC.setAttribute('width', this.width);
                    oC.setAttribute('height', this.height);
                    oC.setAttribute('id', 'canvas');
                    oC.style.backgroundColor = '#000';
                    document.body.appendChild(oC);
                }
            }
            var curWinWidth = window.innerWidth,
                curWinHeight = window.innerHeight;
            var oCanvas = new Canvas(curWinWidth, curWinHeight);
            oCanvas.init();
Copy after login

After calling the init method of the oCanvas object, a canvas will be appended to the end of the body with the id canvas, and the width and height are the same as the width and height of the browser. The height is the same, the background is black, and the effect of snowing at night

Next, there is a stage, and it’s time for the actors to come on stage. How to produce snowflakes? Here, snow-related operations are encapsulated into a class. Its basic structure is as follows:

var Snow = function(){}
Snow.prototype = {
  init : function(){},
  draw : function( cxt ) {},
  update : function(){}
}
Copy after login

This class has a total of three methods (init, draw, update).

init: initialization The position (x, y coordinates), speed, and radius of the snowflake (the size of the snowflake, here we represent the snowflake as a circle with different radii)

function random(min, max) {
                return Math.random() * (max - min) + min;
            }
            init: function () {
                    this.x = random(0, width);
                    this.y = 0;
                    this.r = random(1, 5);
                    this.vy = random(3, 5);
                }
Copy after login

Then init plus this random function can complete the initialization of the snowflake

1. When snowflakes come out, they usually appear at the top of the screen, so the y-coordinates of snowflakes are all 0. Secondly, the x-coordinates of snowflakes are random, and their range is from the left side of the screen. To the right, then it is 0 ~ width. This width is the width of the canvas, which is the width of the browser

2. The radius r of the snowflake is set to any value between 1 ~ 5

3. The falling speed of snowflakes is set to a random speed between 3 ~ 5. The snow I made here is falling vertically. You can expand and consider the influence of wind (there must be horizontal speed at this time)

After having these initialization parameters, we improve the draw method and draw snowflakes:

draw: function (cxt) {
                    cxt.beginPath();
                    cxt.fillStyle = 'white';
                    cxt.arc(this.x, this.y + this.r, this.r, 0, Math.PI * 2, false);
                    cxt.fill();
                    cxt.closePath();
                    this.update(cxt);
                },
Copy after login

The parameter cxt is the context of canvas. This function is very simple. It is an arc method calling the value set in init. To draw a circle (snowflake), an update method is called at the end of this method. What does it do? It updates the speed of snowflakes in the vertical direction

update: function (cxt) {
                    if (this.y < height - this.r) {
                        this.y += this.vy;
                    } else {
                        this.init();
                    }
                }
Copy after login

In the update method, we make a boundary judgment: When the snowflakes fall downwards, they will definitely disappear. What to do after they disappear? What to do if the border is not reached?

The height of the canvas minus the radius of the snowflake is the boundary when the snowflake disappears, so this.y < height - this.r If this condition is true, then the snowflake has been floating, we will We need to update the position of the snowflake in the y direction. The snowflake looks like ('it's snowing'). When a snowflake is about to disappear, we move it to the initial position, so that it looks like it is snowing continuously in a circle. , without redrawing the snowflakes (if you do this, it will definitely affect performance, and this special effect will definitely be stuck in the end. This little trick is used by many similar special effects). At this point, the core process has been completed. Next, we will generate a large number of snowflakes.

var snow = [];
            for (var i = 0; i < 500; i++) {
                setTimeout(function () {
                    var oSnow = new Snow();
                    oSnow.init();
                    snow.push(oSnow);
                }, 10 * i);
            }
Copy after login

Generate 500 snowflakes, not all at the same time, and then save these snowflakes to the array snow.

Then, start the timer and let the snowflakes continue to fall,

Regarding the use of requestAnimationFrame, you can refer to my article: [JS Master’s Road] HTML5’s new timer requestAnimationFrame actual progress bar

(function move() {
                oGc.clearRect(0, 0, width, height);
                for (var i = 0; i < snow.length; i++) {
                    snow[i].draw(oGc);
                }
                requestAnimationFrame(move);
            })();
Copy after login

Complete demo code:


    
    
    
    雪花效果 - by ghostwu
    
    



    <script>
        window.onload = function () {
            var Canvas = function (w, h) {
                this.width = w;
                this.height = h;
            }
            Canvas.prototype = {
                init: function () {
                    var oC = document.createElement(&quot;canvas&quot;);
                    oC.setAttribute(&amp;#39;width&amp;#39;, this.width);
                    oC.setAttribute(&amp;#39;height&amp;#39;, this.height);
                    oC.setAttribute(&amp;#39;id&amp;#39;, &amp;#39;canvas&amp;#39;);
                    oC.style.backgroundColor = &amp;#39;#000&amp;#39;;
                    document.body.appendChild(oC);
                }
            }
            var curWinWidth = window.innerWidth,
                curWinHeight = window.innerHeight;
            var oCanvas = new Canvas(curWinWidth, curWinHeight);
            oCanvas.init();

            var oC = document.querySelector(&#39;#canvas&#39;);
            var width = oC.width, height = oC.height, oGc = oC.getContext(&#39;2d&#39;);

            function random(min, max) {
                return Math.random() * (max - min) + min;
            }
            var Snow = function () {

            }
            Snow.prototype = {
                init: function () {
                    this.x = random(0, width);
                    this.y = 0;
                    this.r = random(1, 5);
                    this.vy = random(3, 5);
                },
                draw: function (cxt) {
                    cxt.beginPath();
                    cxt.fillStyle = &amp;#39;white&amp;#39;;
                    cxt.arc(this.x, this.y + this.r, this.r, 0, Math.PI * 2, false);
                    cxt.fill();
                    cxt.closePath();
                    this.update(cxt);
                },
                update: function (cxt) {
                    if (this.y &lt; height - this.r) {
                        this.y += this.vy;
                    } else {
                        this.init();
                    }
                }
            }

            var snow = [];
            for (var i = 0; i &lt; 500; i++) {
                setTimeout(function () {
                    var oSnow = new Snow();
                    oSnow.init();
                    snow.push(oSnow);
                }, 10 * i);
            }

            (function move() {
                oGc.clearRect(0, 0, width, height);
                for (var i = 0; i &lt; snow.length; i++) {
                    snow[i].draw(oGc);
                }
                requestAnimationFrame(move);
            })();
        }
    </script>
Copy after login

The above is the detailed content of How to achieve snow effect in html5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template