Recently, I saw a particle grid animation very dazzling, and I made one, and it was pretty good as the background. CSDN cannot upload more than 2m pictures, so simply cut a static picture:
Let ’s start to say how to achieve this effect:
First of all, of course, add a canvas:
<canvas id = canvas> </canvas>
The following style:
<Style> #canvas {position: absolute; display: block; left: 0; top: 0; background: #0f0f0f; z -index: -1;} </style>The role of the Z -Index: -1 of Canvas above is that it can be placed under the background of some elements.
In order to ensure that Canvas can be filled with the entire browser, it is necessary to set the wide height of Canvas to the same as the browser:
Function getsize () {w = canvas.width = window.innerWidth; h = Canvas.Height = Window.Innerheight;}The above W and H represent the width of the browser.
Get the width of the browser, and the next step is to draw particles. Here we need to define the parameters of some particles in advance:
VAR OPT = {ParticleAmount: 50, // The number of particles defaultspeed: 1, // The particle motion speed VariantSpeed: 1, // The variable of the particle movement speed: RGB (32,245,245), // The color of the particles linecolor : RGB (32,245,245 ), // The color of the grid connection DEFAULTRADIUS: 2, // The particle radius variantradius: 2, // The variable of the particle radius Mindistance: 200 // The minimum distance between the particles};The speed variables and radius variables above are to ensure that the size and speed of the particles are not exactly the same.
Then we create a class to initialize particles. The code is relatively long, and I have added a comment:
Function partical () {this.x = math.random ()*w; // The x -axis coordinate of the particles this.y = math.random ()*h; // The y -axis coordinate of the particles this.speed = optionspeed + opt.variantSpeed*math.random (); // The movement speed of the particles this.directionangle = math.floor (math.random ()*360); // The direction of the particle movement this.Color = OPT.ParticLeColor; // The color of the particles this.radius = opt.defaultradius+math.random () * opt.variantradius; // The radius of the particles = {x: this.speed * math.direc tionangle), // particle Speed at the X -axis y: this.speed * math.sin (this.directionangle) // The speed of the particles at the y -axis} this.Update = function () {// particle update function this.Border (); ////// Determine whether the particles reach the border this.x += this.vector.x; // The particle in the next moment at the coordinates of the X -axis this moment this.y += this.vector.y; // The particles of the particles will be at the coordinate of the y -axis next moment} This.Border = Function () {// Judging that particles have reached the border if (this.x> = w || this.x <= 0) {// The negative number this.vector.x *= -1;} if (this.y> = h || this.y <= 0) {// If it reaches the upper and lower borders, make the speed of the y -axis into the original negative number This This .vector.y *= -1;} if (this.x> w) {// The following is the operation of changing the browser window in the size of the size, and some particles after the size of the window will be hidden. .x = w;} if (this.y> h) {this.y = h;} if (this.x <0) {this.x = 0;} if (this.y <0) {this.yy = 0;} This.draw = Function () {// Draw the function of the particles ctx.beginpath (); ctx.closepath (); ctx.fillstyle = this.color; ctx.fill ();}}1. The initial speed and angle of each particle is randomly generated, and the color of the particles is determined by the relevant setting options.
2. This.vector is used to store the movement direction of the particles: if this.vector.x is 1, the particles move to the right; if it is -1, the particles move to the left. Similarly, if this.vector.y is negative, the particles move upward, and if it is positive, the particles move downward.
This.Update is used to update the coordinates of the next position of each particle. First, the edge detection is performed; if the movement of the particles exceeds the size of the Canvas, the direction vector is multiplied by -1 to generate reverse movement direction.
3. The window zoom may cause the particles to exceed the boundary, so that the edge detection function cannot be captured, so a series of IF statements are needed to detect this situation and reset the position of the particles to the current Canvas boundary.
4. Draw these points on the canvas in the last step.
The particles of the particles have been written, and he will draw him below:
Function init () {getSize (); for (let i = 0; i <ompt.particalAmount; i ++) {partical.push (new partical ());} loop ();}The above initialization of Opt.particalAmount has a particle object, which initializes the object but it is not drawn. Below is the LOOP function:
Function loop () {ctx.clearrect (0,0, w, h); for (let i = 0; i <partical.length; i ++) {particle [i] .update (); particle [i] .draw ( );} Window.requestanimationFrame (loop);}Each time the loop () function is executed, the content on the Canvas will be removed, and then the particle coordinate is re -calculated through the update () function of the particle object, and the particles are drawn through the Draw () function of the particle object. The following is the effect at this time:
However, after the size of the browser window changes, some particles will disappear. At this time, 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. You need to pay attention here. When the browser is changed, the number of times that triggers the Resize event will be particularly frequent. The edge of the browser is slightly moved. Ten browsers size and more consumed performance. You can test this. Here you can say the solution directly. In fact, what we want is only the last size after the browser changes. So when we change the browser window, it delays 200 milliseconds to execute the computing browser size. If the Resize event is triggered during this period, it will delay 200 milliseconds. It sounds complicated. In fact, the code is simple:
VAR PARTICLLE = [], w, h; // particle array, browser width high delay = 200, tid; // delay execution events and settimeout events. unction () () {getSize (); // Get the browser width and height, there is an introduction to}, delay)} at the top of the articleIn this way, all the particle animation is completed, and then we can draw a line between particles. There is a Mindistance variable in the OPT object defined above. When the connection between the two particles is smaller than this value, we will then we will Draw it between them.
So how to calculate the distance between the two particles, you can think about the first lesson of junior high school mathematics, the pyrothebroken theorem, the square and the square and the square and the right triangle of the right triangle are equal to the square of the third change. See the following:
We now know the coordinates of the X -axis and Y axis of each particle, then we can calculate the distance between the two points, write a function, and pass the two points, as follows:
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 calculate the distance between all each particle and all other particles to determine whether they need to connect. Of course, if the color depth of all particles is exactly the same, it is a bit a bit It is ugly, so we can determine the transparency of the connection according to the distance between the two particles. The closer the distance between the two particles, the more opaque, the farther the distance, and the more transparent, the more than a certain distance will not be displayed.
Function Linepoint (Point, Hub) {for (let i = 0; i <hub.length; i ++) {let distance = getDistance (point, hub [i]); CE; if (if (if (if (if (if ( opacity> 0) {ctx.lineWidth = 0.5; ctx.Strokestyle = rgba (+line [0]+,+line [1]+,+line [2]+,+opacity+); ctx.beginpath (); ctx. moveto (point.x, point.y); ctx.lineto (hub [i] .x, hub [i] .y); ctx.closepath (); ctx.stroke ();}}}}}}}}}}}}}The two parameters transmitted above are the array of one point and the entire point, letting opacity = 1 -distance/optionistance; used to determine the transparency between the connection and also judge the distance. When the distance is greater than Opt.Mindistance, OPACITY is negative, and the following judgments are filtered out. The color above uses regular expressions. You need to analyze the color given in the top OPT object first, and then add transparency. This code is as follows:
var line = option.linecolor.match (// d+/g);
Finally, the distance calculation distance is continuously circulated in the loop () function. Add the code to the loop () as follows:
Function loop () {ctx.clearrect (0,0, w, h); for (let i = 0; i <partical.length; i ++) {particle [i] .update (); particle [i] .draw ( );} for (let i = 0; i <particle.Length; I ++) {// add this cyclic LINEPOINT (particle [i], particle)} Window.requestanimationFrame (loop);}It should be pointed out that if you add too much point to/or too much connection distance (the connection distance will create too much lines), the animation will not be carried. When the view port narrows, it is best to reduce the movement speed of the particles: the smaller the size of the particles, and the movement speed in the narrow space seems faster.
Show the entire code:
<! Doctype html> <html Lang = EN> <Head> <Meta Charset = UTF-8> <Title> Canvas particle animation </Title> <Style> #Canvas {positive: absolute; Display: Block; Block; left: 0; TOP: 0; Background: #00F0F0F; Z -index: -1;} </style> </head> <body> <canvas id = canvas> </canvas> <script> VAR canvas = document.getelementByid ( Canvas) ; VAR CTX = Canvas.getContext (2D); VAR OPT = {ParticleAmount: 50, // The number of particles defaultSpeed: 1, // Motor -speed VariantSpeed: 1, // The variable PARTICLLECOLOR: RG B (32,245,245) , // The color of the particles Linecolor: RGB (32,245,245), // The color of the grid connecting the color defaultradius: 2, // particle radius Variantradius: 2, // The variable mindistance of the particle radius: 200 // The connected wire between the particles Minimum distance}; var line = Opt.linecolor.match (// d+/g); console.log (line); var party = [], w, h; var delay = 200, tid; init (); window. addeventristener (resize, function () {winresize ()}, false); function winresize () {clearout (tid); tid = settimeout (function () {); }, delay)} Function Init () {Getsize (Getsize ); free (let i = 0; I <Opt.particalAmount; i ++) {partical.push (new partical ());} loop (); ); free (let i = 0; i <particle.Length; I ++) {partic [i] .UPDATE (); Particle [i] .draw ();} for (let i = 0; i << / partic.length; I ++) {LinePoint (Particle [i], Particle)} Window.requestanimationFrame (loop);} Function Linepoint (Point, Hub) {for (let i = 0; I <hub.length; I ++) let dispance = getDistance ( Point, hub [i]); Let Opages = 1 -Distance/Opt.mindistance; if (opacity> 0) {ctx.lineWidth = 0.5; ctx.Strokestyle = RGBA (+Line [0]+,+Line [1] +,+line [2]+,+opacity+); ctx.beginpath (); ctx.moveto (point.x, point.y); ctx.lineto (hub [i] .x, hub [i] .y) ; ctx.closepath (); ctx.Stroke ();}} Function GetDistance (Point1, Point2) {Return math.sqrt (math.pow (Point1.x-pill2.x, 2) + math.pow (pings1 Then, then Y -Point2.y, 2));} Function Getsize () {w = canvas.width = window.innerWidth; h = canvas.height = window.innerheight; is.x = math.random ( )*w; // The x -axis coordinate of the particles this.y = math.random ()*h; // The y -axis coordinate this.Speed = OPT.DEFAULTSPED + OPT.VariantSpeed*math.random (); /// The movement speed of the particles is.directionangle = math.floor (math.random ()*360); // The direction of the particle movement this.color = OPT.particleColor; // The color of the particle This.radius = Opt.DefaultRadrad IUS+Math. Random () * Opt.variantradius; // The radius size of the particles this.Vector = {x: this.Speed * math.cos (this.directionangle), // The speed of the particles in the X -axis y: this.Speed * math. sin (this.directionangle) // The speed of the particles at the y -axis} this.Update = FUNCTION () {// The update function of the particles this.Border (); // determine whether the particles reached the border this.x += this.Vector .x; // The coordinates of the x -axis at the next moment at the coordinates of the x -axis at the next moment this.y += this.vector.y; // The particle in the next moment at the coordinates of the y -axis} this.Border = function () {// Judging that the particle is the particle is the particle is They all reach the border if (this.x> = w || this.x <= 0) {// If you reach the left and right boundaries, make the speed of the X -axis turn into the original negative number this.vector.x *= -1;} If (this.y> = h || this.y <= 0) {// If it reaches the upper and lower boundaries, the speed of the y -axis will turn into the original negative number this.vector.y *= -1; .x> w) {// The following is the operation of changing the browser window in size and hour. After the size of the window is changed, some particles will be hidden, so that he can display this.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 () {{{ // The function of drawing particles ctx.beginpath (); ctx.arc (this.x, this.y, this.radius, 0, math.pi * 2); ctx.fillStyle = this.Color ; ctx.fill ();}} </script> </body> </html>The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.