In website or game development, we often need to achieve the effects of snow, rain, and butterflies. These effects share a large degree of randomness, which is an overall trend of animation. Math. the random () method provides us with a random function. The setinterval () method provides us with a short-cycle call function. With these two methods, we can achieve this group animation effect, such as the snow effect (although somewhat rough, but the basic principle is similar ).
Step 1: create a dynamic element library, such as Snowflake, raindrops, and butterflies.
VaR IMG = {1: " "}
The aboveCodeIn, we chose three different snowflake images, which are in transparent PNG format and the size is unified.
Step 2: implement the snowflake removal method, that is, we insert a snowflake in the <body> label, let it follow a certain trajectory, and finally delete it.
Function losesnow () {var posx = parseint (1366 * Math. random (); // generates a random number ranging from 1 to 1366, that is, a random position var posx2 = parseint (* Math. random (); var img_index = parseint (3 * Math. random () + 1; // generates a random number of 1-3, which is used to retrieve a snowflake from the IMG object. Because the image name is convenient, you can skip the IMG object.
// Generate an IMG label so that its initial position is a random vertex var IMG =$ (" "); $ ("body "). append (IMG); IMG. animate ({top: "800px", left: posx2}, 10000); // the IMG trajectory is from one position in 1366 to another, but vertically down setTimeout (function () {// and delete the snowflake after 10 seconds to release the memory IMG. remove ();}, 10000 );}
The above method generates a snowflake at a random position on the top of the browser, drops down to another random position 800 pixels from the top of the browser, and finally deletes the released memory.
The last step is very simple. We call the method above to start heavy snow in the sky.
Setinterval (function () {// generates a snowflake losesnow () ;}, 2) every 2 milliseconds );
In this example, we will share with you the basic principles of special effects. However, JavaScript animation principles are inseparable. In addition, JS animations consume device resources, especially on mobile phones. At present, we recommend that you use the css3 animation function to improve the efficiency of special effects.ProgramEfficiency.