search
HomeWeb Front-endHTML TutorialHow to achieve snow effect in html5

How to achieve snow effect in html5

May 17, 2018 pm 04:14 PM
h5html5method

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();

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(){}
}

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);
                }

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);
                },

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();
                    }
                }

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

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

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);
            })();

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>

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!

Statement
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
HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.