search
HomeWeb Front-endH5 TutorialHTML5 canvas realizes the special effect of falling snowflakes_html5 tutorial skills

I have seen many displays on the Internet showing the effect of html5 snowflakes flying, which is indeed very fascinating. I believe that everyone is as excited as me and is also very curious and wants to study how to implement the code; although these can be downloaded from many places Source code, but I don’t know other people’s ideas and analysis of difficulties when making such animations.

I just happened to study a lot these days, and I am taking advantage of the time now to dissect it 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:

Picture 1

1. Demand analysis

1. Round snowflake

The snowflake shape in this example uses a circle

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 entire 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 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 are falling, 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 and 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; while the snowflakes are falling, their radius remains unchanged and the coordinates are within a certain range. changes, so the coordinates are also random numbers at this time——Math.random()

3. Programming

1. Preparation

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

HTML code:

XML/HTML CodeCopy content to clipboard
  1. canvas id="mycanvas" >
  2. Your browser does not support canvas
  3. canvas> 

CSS code:

CSS CodeCopy content to clipboard
  1. * {
  2. margin: 0;
  3. padding: 0;
  4. }
  5.                                                        
  6. #mycanvas { 
  7. background: black;
  8. }
The effect at this time 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 fills the screen

The JavaScript code is as follows:

JavaScript Code
Copy content to clipboard
  1. //Get mycanvas canvas
  2. var can = document.getElementById("mycanvas");
  3. var ctx = can.getContext("2d");
  4. //Canvas width
  5. var wid = window.innerWidth;
  6. //Canvas height
  7. var hei = window.innerHeight;
  8. can.width=wid;
  9. can.height=hei;

The effect at this time 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;

When generating 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 is used .random() generates radius and coordinates (X, Y) for 100 snowflakes respectively;

Then 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:

JavaScript CodeCopy content to clipboard
  1. //Number of snowflakes
  2. var snow = 100;
  3. //Snowflake coordinates, radius
  4. var arr = []; //Save the coordinates and radius of each circle
  5. for (var i = 0; i
  6. arr.push({
  7. x: Math.random() * wid,
  8. y: Math.random() * hei,
  9. r: Math.random() * 10 1
  10. })
  11. }


4. Draw snowflakes

We have generated 100 snowflake radii and coordinates (X, Y) above. The following is to use canvas to draw snowflakes (here, we draw circles). Here we define a function

The JavaScript code is as follows:

JavaScript CodeCopy content to clipboard
  1. //Drawing snowflakes
  2. function DrawSnow() {
  3. ctx.fillStyle="white";
  4. ctx.beginPath();
  5.  for (var i = 0; i
  6. var p = arr[i];
  7. ctx.moveTo(p.x,p.y);
  8. ctx.arc(p.x,p.y,p.r,0,2*Math.PI,false);
  9. }
  10. ctx.fill();
  11. 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). Once you do this, you are 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, 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 keep moving.

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

At the same time, the coordinates (X, Y) of each snowflake need to be constantly changed (within a certain range). The snowflakes here fall from the upper left to the lower right, so the X and Y coordinate values ​​​​of each snowflake are in Keep increasing, then we use a function SnowFall() to define the snowflakes falling rules

The function code is as follows:

JavaScript CodeCopy content to clipboard
  1. //雪花飘落   
  2. function SnowFall() {   
  3.     for (var i = 0; i 
  4.         var p = arr[i];   
  5.         p.y  = Math.random() * 2   1;   
  6.         if (p.y > hei) {   
  7.             p.y = 0;   
  8.         }   
  9.         p.x  = Math.random() * 2   1;   
  10.         if (p.x > wid) {   
  11.             p.x = 0;   
  12.     "white-space:pre">    }   
  13.     }   
  14. }  


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

此时DrawSnow函数定义如下:

JavaScript Code复制内容到剪贴板
  1. //画雪花   
  2. function DrawSnow() {   
  3.     ctx.clearRect(0, 0, wid, hei);   
  4.     ctx.fillStyle = "white";   
  5.     ctx.beginPath();   
  6.     for (var i = 0; i 
  7.         var p = arr[i];   
  8.         ctx.moveTo(p.x, p.y);   
  9.         ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
  10.     }   
  11.     ctx.fill();   
  12.     SnowFall();   
  13.     ctx.closePath();   
  14. }   

最后执行setInterval(DrawSnow, 50); 

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

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

XML/HTML Code复制内容到剪贴板
  1. html>  
  2. html>  
  3.   
  4.     head>  
  5.         meta charset="utf-8" />  
  6.         title>title>  
  7.         script src="js/jquery-1.8.3.min.js">script>  
  8.         style type="text/css">  
  9.             * {   
  10.                 margin: 0;   
  11.                 padding: 0;   
  12.             }   
  13.                
  14.             #mycanvas {   
  15.                 background: black;   
  16.             }
  17. style>
  18.  head> 
  19. body>
  20.  canvas id="mycanvas" >
  21. Your browser does not support canvas
  22. canvas>
  23. script>
  24. //Get mycanvas canvas
  25. var can = document.getElementById("mycanvas");
  26. var ctx = can.getContext("2d");
  27. //Canvas width
  28. var wid = window.innerWidth;
  29. //Canvas height
  30. var hei = window.innerHeight;
  31. can.width = wid;
  32. can.height = hei;
  33. //Number of snowflakes
  34. var snow = 100;
  35. //Snowflake coordinates, radius
  36. var arr = []; //Save the coordinates and radius of each circle
  37. for (var i = 0; i snow; i ) {
  38. arr.push({
  39. x: Math.random() * wid,
  40.                     y: Math.random() * hei,   
  41.                     r: Math.random() * 10   1   
  42.                 })   
  43.             }   
  44.             //画雪花   
  45.             function DrawSnow() {   
  46.                 ctx.clearRect(0, 0, wid, hei);   
  47.                 ctx.fillStyle = "white";   
  48.                 ctx.beginPath();   
  49.                 for (var i = 0; i  snow; i ) {   
  50.                     var p = arr[i];   
  51.                     ctx.moveTo(p.x, p.y);   
  52.                     ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
  53.                 }   
  54.                 ctx.fill();   
  55.                 SnowFall();   
  56.                 ctx.closePath();   
  57.             }  
  58.             //雪꽃飘落   
  59.             기능 SnowFall() {   
  60.                for (var i = 0; i  ;  i ) {   
  61.                    var p = arr[i];   
  62.                    p.y  = Math.random() * 2   1;   
  63.                   if (p.y > hei) {   
  64.                        p.y = 0;   
  65.                    }   
  66.                    p.x  = Math.random() * 2   1;   
  67.                   if (p.x > wid) {   
  68.                       p.x = 0;   
  69.                    }   
  70.                 }   
  71.             }   
  72.             setInterval(DrawSnow, 50);   
  73.         스크립트>  
  74.     본체>  
  75.   
  76. html>  
  77.   

好了,今天分享就到这里,希望对大家的文习有所帮助。
원문:http://www.cnblogs.com/tangyifeng/p/5253629.html

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
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.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools