Create a dynamic particle mesh animation using HTML5 Canvas,

Source: Internet
Author: User

Create a dynamic particle mesh animation using HTML5 Canvas,

Recently, I saw a very dazzling particle mesh animation, and I made it myself. The background was quite good. CSDN cannot upload images larger than 2 MB, so it simply captures a static image:

Let's start to explain how to achieve this effect:

First, add a canvas:

<canvas id="canvas"></canvas>

The following is a style:

<style>    #canvas{        position: absolute;        display: block;        left:0;        top:0;        background: #0f0f0f;        z-index: -1;     }</style>

The z-index:-1 of canvas can be placed under some elements as the background.

To ensure that the canvas can be filled with the entire browser, set the width and height of the canvas to the same as that of the browser:

function getSize(){    w = canvas.width = window.innerWidth;    h = canvas.height = window.innerHeight;}

The preceding w and h represent the width and height of the browser respectively.

After obtaining the width and height of the browser, we will draw particles in it. here we need to define some particle parameters in advance:

Var opt = {MAID: 50, // number of particles ultultspeed: 1, // particle motion speed variantSpeed: 1, // particle motion speed variable particle color: "rgb (32,245,245) ", // the color of the particle lineColor:" rgb (32,245,245) ", // the color of the mesh line defaultRadius: 2, // The particle radius variantRadius: 2, // minDistance, variable of particle radius: 200 // minimum distance between particles };

The preceding velocity and radius variables are used to ensure that the particle size and velocity are not the same.

Then we create another class to initialize the particle. The code is long and I have added notes:

Function Partical () {this. x = Math. random () * w; // X axis coordinate of the particle this. y = Math. random () * h; // y axis of the particle this. speed = opt. defaultSpeed + opt. variantSpeed * Math. random (); // the velocity of the particle movement this. direangle angle = Math. floor (Math. random () * 360); // the direction of the particle motion this. color = opt. particle color; // the color of the particle. this. radius = opt. defaultRadius + Math. random () * opt. variantRadius; // particle radius size this. vector = {x: this. speed * Math. cos (this. direangle angle), // The Particle speed on the X axis y: this. speed * Math. sin (this. direangle angle) // the speed of the particle on the Y axis} this. update = function () {// particle update function this. border (); // determines whether the particle has reached the boundary this. x + = this. vector. x; // the coordinate of the next moment engraved on the x axis of the particle. this. y + = this. vector. y; // the coordinate of the moment when the particle is engraved on the y axis} this. border = function () {// determines if (this. x> = w | this. x <= 0) {// If the left and right boundary is reached, the x-axis speed is changed to the original negative value. this. vector. x * =-1;} if (this. y> = h | this. y <= 0) {// if it reaches the upper and lower boundary, the y-axis speed will be changed to the original negative number this. vector. y * =-1;} if (this. x> w) {// The following is the operation to change the browser window size. After the window size is changed, some particles are hidden and displayed. x = w;} if (this. y> h) {this. y = h;} if (this. x <0) {this. x = 0;} if (this. y <0) {this. y = 0 ;}} this. draw = function () {// draw the particle function ctx. beginPath (); ctx. arc (this. x, this. y, this. radius, 0, Math. PI * 2); ctx. closePath (); ctx. fillStyle = this. color; ctx. fill ();}}

1. The initial velocity and angle of each particle are randomly generated. The color of the particle is determined by related settings.

2. this. vector is used to store the moving direction of the particle. If this. vector. x is 1, the particle moves to the right. If it is-1, the particle moves to the left. Similarly, if this. vector. y is negative, the particle moves up. If it is positive, the particle moves down.

This. update is used to update the coordinates of the next position of each particle. First, perform edge detection. If the moving of a particle exceeds the size of the canvas, multiply the direction vector by-1 to generate a reverse direction of motion.

3. Window Scaling may cause the particle to go beyond the boundary. As a result, the edge detection function cannot be captured. Therefore, a series of if statements are required to detect this situation, resets the position of the particle to the boundary of the current canvas.

4. Draw the points on the canvas in the last step.

After the class of the particle has been written, we will plot it as follows:

function init(){   getSize();   for(let i = 0;i<opt.particleAmount; i++){        particle.push(new Partical());   }   loop();}

The above initialization of the opt. Particle amount particle object, initialization of the object but not drawn out, the following is the loop function:

function loop(){    ctx.clearRect(0,0,w,h);    for(let i = 0;i<particle.length; i++){        particle[i].update();        particle[i].draw();    }    window.requestAnimationFrame(loop);}

Every time the loop () function is executed, the content on the canvas is cleared, and then the particle coordinate is recalculated through the update () function of the particle object. Finally, the draw () of the particle object is used () function to draw particles. The following figure shows the effect at this time:

However, after the browser window size changes, some particles will disappear. In this case, you need to add an event to monitor whether the browser size changes:

window.addEventListener("resize",function(){    winResize()},false);

Then you need to write the winResize () function. Note that when the browser changes, the number of times the resize event is triggered is very frequent, just move the edge of the browser to trigger dozens of resize events, and the browser size will be recalculated dozens of times, which consumes a lot of performance. You can test this, let's talk about the solution. In fact, all we need is the last size after the browser changes. As for how many changes in the middle, it has nothing to do with us, therefore, when the browser window changes, we can delay the task of calculating the browser size by 200 milliseconds. If the resize event is triggered during this period, it will be delayed by 200 milliseconds, it sounds complicated, but the code is actually very simple:

Var particle = [], w, h; // particle array, browser width and height var delay = 200, tid; // function winResize () is referenced by the delayed execution event and setTimeout event () {clearTimeout (tid); tid = setTimeout (function () {getSize (); // get the width and height of the browser, which is described at the top of the article}, delay )}

In this way, all the particle animations are completed, and then we can draw lines between particles. The opt object defined above contains a minDistance variable, when the line between two particles is smaller than this value, we will draw a line between them.

So how can we calculate the distance between two particles? You can think back to the first class of junior high school mathematics, the stock theorem, and the sum of the squares of the two Straight corners of the right triangle is equal to the square of the third change. Let's look at the following:

Now that we know the coordinates of the X and Y axes of each particle, we can calculate the distance between two points. Write a function and input two points, as shown below:

function getDistance(point1,point2){        return Math.sqrt(Math.pow(point1.x-point2.x,2) + Math.pow(point1.y - point2.y ,2));    }

Now we can calculate the distance between two points, so we can calculate the distance between each particle and all other particles to determine whether they need to be connected, of course, if the color depth of all particles is the same, it will be a bit ugly. Therefore, we can determine the transparency of the line based on the distance between the two particles. The closer the two particles are, the more opaque they are, the farther the distance is, the more transparent it is. If the distance is exceeded, it is not displayed.

function linePoint(point,hub){    for(let i = 0;i

The two parameters passed in above are an array of one vertex and the entire vertex respectively. let opacity = 1-distance/opt. minDistance is used to determine the transparency between connections and determine the distance. The distance is greater than opt. when minDistance is used, the opacity is negative. When the following judgment is performed, It is filtered out. The above color uses a regular expression. You need to first parse the color given in the top opt object, and then add transparency, the Code is as follows:

var line = opt.lineColor.match(/\d+/g);

Finally, the distance can be calculated cyclically in the loop () function. After the code is added to the loop (), it is as follows:

Function loop () {ctx. clearRect (0, 0, w, h); for (let I = 0; I <particle. length; I ++) {particle [I]. update (); particle [I]. draw () ;}for (let I = 0; I <particle. length; I ++) {// added this cyclic linePoint (particle [I], particle)} window. requestAnimationFrame (loop );}

It should be pointed out that if too many points and/or too many connections are added (the connection distance will create too many lines), the animation will not be able to hold the animation. It is best to reduce the moving speed of a particle when the viewport is narrow: the smaller the particle size, the faster the moving speed in the narrower space seems to be.

Show the entire code segment:

<! DOCTYPE html> 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.