search
HomeWeb Front-endH5 TutorialHow to use HTML5 canvas to make snowflakes fall

This article mainly introduces in detail the HTML5 canvas to achieve the special effect of falling snowflakes. The effect achieves a fascinating and realistic animation effect. Interested friends can refer to it.

I have seen many displays of HTML5 on the Internet. The effect of flying snowflakes is indeed very fascinating. I believe that everyone is as excited as me when watching it. They are also curious and want to study how to implement the code. Although these source codes can be downloaded from many places, I don’t know anyone else has made this. Analysis of ideas and difficulties in animation-like animation.

I just happened to study a little these days, and I took advantage of the time to dissect the needs step by step from demand analysis, knowledge points, and programming. If I try to make a fool of myself in front of you, please don’t laugh. .

The final rendering is as follows:

Figure 1

1. Requirements analysis

1. Circular snowflakes

In this example, the shape of the snowflakes is circular

2. The number of snowflakes is fixed

Carefully observe the number of white snowflakes according to Figure 1. During the falling process, The number of snowflakes in the picture should be fixed. This requirement needs to be obtained through our observation and analysis. This is consistent with the scene we see in real life where snowflakes are flying all over the sky.

3. The size of snowflakes is inconsistent

Each snowflake has a different size, which means that the radius of the snowflake is random. This is consistent with the scene where we see snowflakes flying all over the sky in real life.

4. The position of the snowflakes is moving

Snowflakes fall, and naturally their positions are also moving.

2. Knowledge points

1. Use Html5 Canvas JavaScript to draw a circle - forming a circular snowflake

In Html5, you need to use Canvas at the same time Use JavaScript to draw a circle to form a circular snowflake—arc(x,y,r,start,stop);

2. Random numbers—generate circular snowflakes with different radii and coordinates

In this example, when the web page is loaded for the first time, a certain number of snowflakes with different radii and positions need to be generated, so the radius and coordinates are random numbers; during the falling process of the snowflakes, the radius remains unchanged and the coordinates change within a certain range. Therefore, the coordinates are also random numbers at this time - Math.random()

3. Programming

1. Preparation work

Put a canvas and set the background color of the entire body to black

HTML code:

<canvas id="mycanvas">
    您的浏览器不支持canvas画布   
</canvas>

CSS code:

* {   
    margin: 0;   
    padding: 0;   
}   
#mycanvas {   
    background: black;   
}

The effect is as follows:

Note: canvas has an initialized height and width by default, so you don’t have to worry about it

2. The canvas displays full screen

The JavaScript code is as follows:

//获取mycanvas画布   
    var can = document.getElementById("mycanvas");   
    var ctx = can.getContext("2d");   
    //画布宽度   
    var wid = window.innerWidth;   
    //画布高度   
    var hei = window.innerHeight;   
    can.width=wid;   
    can.height=hei;

The effect is as follows:

3. Initialization generates a fixed number of snowflakes

According to our above demand analysis and interpretation of knowledge points, first of all, the number of snowflakes is fixed, so we need to define a variable var snow = 100; here it is assumed that the number of snowflakes is 100,;

Generate When it comes to snowflakes, the radius and position of each snowflake are different. We regard each snowflake as an object, then the properties of this object include: radius, coordinates (X, Y), then a snowflake object can be written as var snowOject={x :1,y:10,r:5}, here represents a circular snowflake with coordinates (1,10) and radius 5; in this example, since the radius and coordinates are random numbers, Math.random() is used Generate radius and coordinates (X, Y) for 100 snowflakes respectively;

We have 100 snowflakes here, so in order to facilitate subsequent operations, we use an array to save these 100 snowflake objects.

The JavaScript code is as follows:

//雪花数目   
var snow = 100;   
//雪花坐标、半径   
var arr = []; //保存各圆坐标及半径   
for (var i = 0; i < snow; i++) {   
arr.push({   
x: Math.random() * wid,   
y: Math.random() * hei,   
r: Math.random() * 10 + 1   
})   
}

4. Drawing snowflakes

Above we have generated 100 snowflake radius and coordinates (X, Y), The following is a cycle of using canvas to draw snowflakes (here, drawing a circle). A function is defined here

The JavaScript code is as follows:

//画雪花   
function DrawSnow() {   
    ctx.fillStyle="white";   
    ctx.beginPath();   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        ctx.moveTo(p.x,p.y);   
        ctx.arc(p.x,p.y,p.r,0,2*Math.PI,false);   
    }   
    ctx.fill();   
  
    ctx.closePath();

Then call the DrawSnow() function, the effect is as follows:

You can try to refresh the webpage multiple times to see if snowflakes of different sizes and positions will be generated (normally, it is possible). If you do this, you will be close to the final effect

Note: Since 100 circles need to be drawn here, the drawing start coordinates are redefined every time a circle is drawn: ctx.moveTo(p.x,p.y); otherwise strange effects will occur. If you don’t believe it, you can try it

5. Snowflakes fluttering

We have drawn 100 snowflakes above. Unfortunately, we can only see the changing effect by refreshing the web page, but what we need to achieve is that the snowflakes do not The moving position of the stop.

First we need to use the setInterval function to continuously redraw the snowflakes. The interval here is 50 milliseconds: setInterval(DrawSnow,50);

同时每一朵雪花的坐标(X、Y)需要不停的改变(在一定幅度内),我们这里的雪花是从左上方飘落到右下方,所以每朵X、Y坐标值都在不停的增大,那我们用一个函数SnowFall()定义雪花飘过规则

该函数代码如下:

//雪花飘落   
function SnowFall() {   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        p.y += Math.random() * 2 + 1;   
        if (p.y > hei) {   
            p.y = 0;   
        }   
        p.x += Math.random() * 2 + 1;   
        if (p.x > wid) {   
            p.x = 0;   
    <span style="white-space:pre">    </span>}   
    }   
}

然后将该函数放入DrawSnow()执行,注意:我们每隔50毫毛重画雪花,必须擦除画布,所以DrawSnow()函数体内必须在前面执行clearRect()函数,即:ctx.clearRect(0, 0, wid, hei);

此时DrawSnow函数定义如下:

//画雪花   
function DrawSnow() {   
    ctx.clearRect(0, 0, wid, hei);   
    ctx.fillStyle = "white";   
    ctx.beginPath();   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        ctx.moveTo(p.x, p.y);   
        ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
    }   
    ctx.fill();   
    SnowFall();   
    ctx.closePath();   
}

最后执行setInterval(DrawSnow, 50); 

OK,经过我们上述步骤,小伙伴们是否已经对整个过程及技术实现很清晰了。

完整代码如下(大家可以直接复制到自己项目中执行,测试下效果):

<!DOCTYPE html>  
<html>  
  
    <head>  
        <meta charset="utf-8" />  
        <title></title>  
        <script src="js/jquery-1.8.3.min.js"></script>  
        <style type="text/css">  
            * {   
                margin: 0;   
                padding: 0;   
            }   
               
            #mycanvas {   
                background: black;   
            }   
        </style>  
    </head>  
  
    <body>  
        <canvas id="mycanvas">  
            您的浏览器不支持canvas画布   
        </canvas>  
        <script>  
            //获取mycanvas画布   
            var can = document.getElementById("mycanvas");   
            var ctx = can.getContext("2d");   
            //画布宽度   
            var wid = window.innerWidth;   
            //画布高度   
            var hei = window.innerHeight;   
            can.width = wid;   
            can.height = hei;   
            //雪花数目   
            var snow = 100;   
            //雪花坐标、半径   
            var arr = []; //保存各圆坐标及半径   
            for (var i = 0; i < snow; i++) {   
                arr.push({   
                    x: Math.random() * wid,   
                    y: Math.random() * hei,   
                    r: Math.random() * 10 + 1   
                })   
            }   
            //画雪花   
            function DrawSnow() {   
                ctx.clearRect(0, 0, wid, hei);   
                ctx.fillStyle = "white";   
                ctx.beginPath();   
                for (var i = 0; i < snow; i++) {   
                    var p = arr[i];   
                    ctx.moveTo(p.x, p.y);   
                    ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
                }   
                ctx.fill();   
                SnowFall();   
                ctx.closePath();   
            }   
            //雪花飘落   
            function SnowFall() {   
                for (var i = 0; i < snow; i++) {   
                    var p = arr[i];   
                    p.y += Math.random() * 2 + 1;   
                    if (p.y > hei) {   
                        p.y = 0;   
                    }   
                    p.x += Math.random() * 2 + 1;   
                    if (p.x > wid) {   
                        p.x = 0;   
                    }   
                }   
            }   
            setInterval(DrawSnow, 50);   
        </script>  
    </body>  
  
</html>

好了,今天分享就到这里,希望对大家的学习有所帮助。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何在canvas里面基于随机点绘制一个多边形

用HTML5 Canvas来绘制三角形和矩形等多边形的方法

The above is the detailed content of How to use HTML5 canvas to make snowflakes fall. 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
HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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