search
HomeWeb Front-endH5 TutorialTutorial on using Canvas in HTML5 combined with formulas to draw particle motion_html5 tutorial skills

Recently, I want to make a web page and put some of the DEMOs I made during the process of learning HTML5 to make a collection. However, it would be too ugly to just make a web page and arrange all the DEMOs one by one. I just thought, since I have learned canvas, let’s play around with the browser and make a small opening animation.

After thinking about the effect of the opening animation for a while, I decided to use particles because I think particles are more fun. I still remember that the first technical blog post I wrote was about particleizing text and pictures: Particleizing text and pictures. At that time, I only did linear motion, and added a little 3D effect. The exercise formula is simple. So I just wanted to make this opening animation more dynamic.

Go to DEMO first: http://2.axescanvas.sinaapp.com/demoHome/index.html

Is the effect more dynamic than linear motion? And it’s really simple, don’t forget the title of this blog post, a little formula, a big fun. To achieve such an effect, all we need is our junior high school. . Or the physics knowledge in high school, the formulas of accelerated motion and decelerated motion. So it's really the little drop formula. The original poster likes to mess around with some cool things. Although he may not use them at work, the fun is really fascinating. Moreover, doing this can also strengthen your programming thinking skills.

Without further ado, let’s get to the topic. Let me briefly explain the principle~~~

The core code of particle motion is just this:

XML/HTML CodeCopy content to clipboard
  1. update:function(time){   
  2.             this.x  = this.vx*time;   
  3.             this.y  = this.vy*time;   
  4.     
  5.             if(!this.globleDown&&this.y>0){   
  6.                 var yc = this.toy - this.y;   
  7.                 var xc = this.tox - this.x;   
  8.     
  9.                 this.jl = Math.sqrt(xc*xc yc*yc);   
  10.     
  11.                 var za = 20;   
  12.     
  13.                 var ax = za*(xc/this.jl),   
  14.                     ay = za*(yc/this.jl),   
  15.                     vx = (this.vx ax*time)*0.97,   
  16.                     vy = (this.vy ay*time)*0.97;   
  17.     
  18.                 this.vx = vx;   
  19.                 this.vy = vy;   
  20.     
  21.             }else {   
  22.                 var gravity = 9.8;   
  23.                 var vy = this.vy gravity*time;   
  24.     
  25.                 if(this.y>canvas.height){   
  26.                     vy = -vy*0.7;   
  27.                 }
  28.  this.vy = vy;
  29.                                                                 
  30. },
Particles have a total of two states, one is free falling, and the other is under suction. Not to mention free fall. Before talking about suction, let’s post the properties of the particles:



JavaScript Code
Copy content to clipboard
  1. var Dot = function(x,y,vx,vy,tox,toy,color){
  2.  
  3. this.x=x; 
  4. this.y=y;
  5.  
  6. this.vx=vx; 
  7.  
  8. this.vy=vy; 
  9. this.nextox = tox;
  10. this.nextoy = toy;
  11.  
  12. this.color = color;
  13. this.visible = true;
  14. this.globleDown = false;
  15. this.setEnd(tox, toy);
  16. }
  17. setEnd:
  18. function(tox, toy){
  19.                                                                             
  20.                                                                                                                                                                                                                                                    .y;
  21.                                                                                          .x;
  22. },
  23. x and y are the positions of the particles, vx is the horizontal velocity of the particles, and vy is the vertical velocity of the particles. It doesn’t matter whether you know nexttox or the like, they are just temporary variables. tox, and toy are the destination locations of the particles.

    First, give all particles a destination, which will be discussed below. That is to say, you want the particle to reach the place, and then define a variable za as the acceleration. If you want to know the specific value, you will get the approximate parameters through more tests. I set it to 20, and it feels about the same. za is the acceleration of the line between the particle and the destination. Therefore, we can calculate the horizontal acceleration and vertical acceleration of the particle through the position of the particle and the position of the destination through simple trigonometric functions. This paragraph

    JavaScript CodeCopy content to clipboard
    1. var ax = za*(xc/this.jl),
    2. ay = za*(yc/this.jl),

    After having horizontal acceleration and vertical acceleration, the next step is even simpler. Calculate the increment of horizontal speed and vertical speed directly, thereby changing the values ​​of horizontal speed and vertical speed

    XML/HTML CodeCopy content to clipboard
    1. vx = (this.vx ax*time)*0.97,
    2. vy = (this.vy ay*time)*0.97;

    The reason why it is multiplied by 0.97 is to simulate energy loss so that the particles will slow down. time is the time difference between each frame

    After calculating the velocity, just update the particle position.

    XML/HTML CodeCopy content to clipboard
    1. this.x = this.vx*time;
    2. this.y = this.vy*time;

    Because the direction of the connection between the particle and the destination is constantly changing during flight, the horizontal acceleration and vertical acceleration of the particle must be recalculated every frame.

    This is the principle of movement, isn’t it very simple?

    Now that we have talked about the principle of motion, let’s talk about the specific implementation of the above animation: animation initialization, draw the desired words or pictures on an off-screen canvas, and then obtain the pixels of the off-screen canvas through the getImageData method. . Then use a loop to find the drawn area in the off-screen canvas. Because the data value in imageData is an rgba array, we judge that the last value, that is, the transparency is greater than 128, means that the area has been drawn. Then get the xy value of the area. In order to prevent too many particle objects from causing page lag, we limit the number of particles. When taking pixels, the x value and y value increase by 2 each time, thereby reducing the number of particles.

    XML/HTML CodeCopy content to clipboard
    1. this.osCanvas = document.createElement("canvas");   
    2.         var osCtx = this.osCanvas.getContext("2d");   
    3.     
    4.         this.osCanvas.width = 1000;   
    5.         this.osCanvas.height = 150;   
    6.     
    7.         osCtx.textAlign = "center";   
    8.         osCtx.textBaseline = "middle";   
    9.         osCtx.font="70px 微软雅黑,黑体 bold";   
    10.         osCtx.fillStyle = "#1D181F"  
    11.         osCtx.fillText("WelCome" , this.osCanvas.width/2 , this.osCanvas.height/2-40);   
    12.         osCtx.fillText("To wAxes' HOME" , this.osCanvas.width/2 , this.osCanvas.height/2 40);   
    13.         var bigImageData = osCtx.getImageData(0,0,this.osCanvas.width,this.osCanvas.height);   
    14.     
    15.         dots = [];   
    16.     
    17.         for(var x=0;xbigImageData.width;x =2){   
    18.             for(var y=0;ybigImageData.height;y =2){   
    19.                 var i = (y*bigImageData.width   x)*4;   
    20.                 if(bigImageData.data[i 3]>128){   
    21.                     var dot = new Dot(   
    22.                         Math.random()>0.5?Math.random()*20 10:Math.random()*20 canvas.width-40,   
    23.                         -Math.random()*canvas.height*2,   
    24.                         0,   
    25.                         0,   
    26.                         x (canvas.width/2-this.osCanvas.width/2),   
    27.                         y (canvas.height/2-this.osCanvas.height/2),   
    28.                         "rgba(" bigImageData.data[i] "," bigImageData.data[i 1] "," bigImageData.data[i 2] ",1)"   
    29.                     );   
    30.                     dot.setEnd(canvas.width/2,canvas.height/2)   
    31.                     dots.push(dot);   
    32.                 }   
    33.             }   
    34.         }   

    通过循环获取到粒子的位置xy值后,把位置赋给粒子,成为粒子的目的地。然后动画开始,就可以做出文字图片粒子化的效果了。


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

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

How to solve the h5 compatibility problemHow to solve the h5 compatibility problemApr 06, 2025 pm 12:36 PM

Solutions to H5 compatibility issues include: using responsive design that allows web pages to adjust layouts according to screen size. Use cross-browser testing tools to test compatibility before release. Use Polyfill to provide support for new APIs for older browsers. Follow web standards and use effective code and best practices. Use CSS preprocessors to simplify CSS code and improve readability. Optimize images, reduce web page size and speed up loading. Enable HTTPS to ensure the security of the website.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),