Make a fireworks effect through js (detailed steps)

Posted by standalone on Wed, 04 Mar 2020 14:37:30 +0100

I believe that everyone has seen fireworks or let them go. After a fireworks is lit, it explodes in the sky. It's cool to think about it, and even cooler. Next, I'll take you to do a cool thing. We can finish a fireworks effect through js.

First, let's describe a night scene on the page:

<style type="text/css">
css Part
			#container{
				width: 80%;
				height: 600px;
				margin: 20px auto;
				background: black;
				border: 2px solid red;
				/*Make a relative position for fireworks*/
				position: relative;
				cursor: pointer;
				/*When the fireworks explode beyond the black screen, the overlay does not display*/
				overflow: hidden;
				
			}
		</style>
html Part
    <body>
		<div id="container"></div>
	</body>

The effect displayed is:

Then a black night is simulated.
The next step is to analyze the whole code. How do fireworks display? They have a heaven effect and explode in the sky.
Then we can divide it into two parts to write, first write the effect of heaven, then go to the designated position and disappear, and then show the effect of explosion.

1. Theme fireworks

Part js

//		1, Theme fireworks
		class Fire{
//			1. Constructor
			constructor(pos){
//				2. Get the black box element
				this.cont = document.getElementById("container");
//              5. Since the coordinates are passed to the new method, the constructor is responsible for receiving (receiving an object)
//                After receiving the object, the key value pair in it is directly parsed to this for easy use in subsequent methods
                 this.x = pos.x;
                 this.y = pos.y
			}
//			3. Create theme fireworks
			create(){
//				3.1 create theme fireworks this.f
				this.f = document.createElement("div");
//				3.2 get its style
				this.f.className = "fire";
//				3.3 random colors by color random function
                this.f.style.background = randomColor();
//				3.4 assign it to a black box
                this.cont.appendChild(this.f);
//              5. The display position of fireworks is the position of the x axis corresponding to the mouse click
                this.f.style.left = this.x + "px";
//              7. Let it move after creation
                this.fireMove();
				
			}
//			6. Let the theme fireworks rise to the height of our mouse click
//           The first parameter of the motion encapsulation function is the element, the second is the required motion attribute and the target position, and the third is the new function
              fireMove(){
              	move2(this.f,{
              		top:this.y,
              	})
              }
		}
//		4.
		var ocont = document.getElementById("container");
		ocont.onclick = function(eve){
//			4.1 define event objects
			var e = eve||event;
//			4.2 get coordinates to prepare for fireworks (coordinate range generated by theme fireworks)
			var x = e.pageX - this.offsetLeft;
			var y = e.pageY - this.offsetTop;
//			4.3 create a fireworks element, and transfer the above coordinates to the past through parameter transfer, which is convenient for use
			var f = new Fire({
				x:x,
				y:y
			});
//			4.4 execute the method of creating fireworks
			f.create();
		}

css needs to add the style of the theme fireworks that need to be added above

<style type="text/css">
			#container{
				width: 80%;
				height: 600px;
				margin: 20px auto;
				background: black;
				border: 2px solid red;
				/*Make a relative position for fireworks*/
				position: relative;
				cursor: pointer;
				/*When the fireworks explode beyond the black screen, the overlay does not display*/
				overflow: hidden;
				
			}
			.fire{
				width: 10px;
				height: 10px;
				position: absolute;
				/*Let the theme fireworks be initially positioned at the bottom of the black frame to pave the sky behind*/
				bottom: 0;
			}
		</style>

Through the above steps, you can create and move the theme fireworks to achieve the effect of theme fireworks rising in the black box (the above code does not add the package function to be added, and I will give you the overall code at the end, hoping that you can understand the effect of theme fireworks rising to the click position through the code I wrote above );

The blue dot is a process that I click the position to create the theme fireworks to rise to the target position (I can try to see the process).
At the beginning, we analyzed that when our fireworks reach the target position, they will explode. At this time, we can remove the theme fireworks and ask them to create small fireworks (the effect of theme fireworks exploding)

2. small fireworks
The css part needs to add the style required by the fireworks

<style type="text/css">
			#container{
				width: 80%;
				height: 600px;
				margin: 20px auto;
				background: black;
				border: 2px solid red;
				/*Make a relative positioning for fireworks*/
				position: relative;
				cursor: pointer;
				/*When the fireworks explode beyond the black screen, the overlay will not be displayed*/
				overflow: hidden;
				
			}
			.fire{
				width: 10px;
				height: 10px;
				position: absolute;
				/*Let the theme fireworks be initially positioned at the bottom of the black frame to pave the sky behind*/
				bottom: 0;
			}
			.small-fire{
				width: 10px;
				height: 10px;
				/*Set to circle*/
				border-radius:50%;
				position: absolute;
			}

Part js

//It is just analyzed that after the theme fireworks are moved, they should disappear to show the effect of small fireworks exploding
//                  8. Remove the subject fireworks instance
                    this.f.remove();
//                  9. Prepare a small fireworks instance and randomly set the number (between 10 and 20) (because it takes many to explode)
                    var randomNum = random(10,20);
//                  10. At the same time of creating a small fireworks instance, pass the required information to facilitate use
                    for(var i = 0; i<randomNum;i++){
//                  	Pass information on
                    	var sf = new smallFire({
//                  		cont: black box, x:left distance (coordinate), y:top distance (coordinate)
                    		cont:this.cont,
                    		x:this.x,
                    		y:this.y
                    	})
//                  	11. And create methods for its execution
                    	sf.create();
                    }

              	})
              }
		}
//		2, Fireworks
          class smallFire{
//        	12. By accepting the parameters and analyzing the object, get the required information for easy use
          	constructor(obj){
            this.cont = obj.cont;
            this.x = obj.x;
            this.y = obj.y;
        }
//        	13. Creation of fireworks
          	create(){
//          13.1 create the elements of the fireworks, get the style, and get its coordinates.
            this.f = document.createElement("div");
            this.f.className = "small-fire";
            this.f.style.background = randomColor();
            this.cont.appendChild(this.f);
            this.f.style.left = this.x + "px";
            this.f.style.top = this.y + "px";
//          15. Let it move directly after creation
            this.smallMove();
          	}
//        	14. Movement of small fireworks
            smallMove(){
            // Because of the free falling effect, the movement of fireworks is not suitable to use the buffering movement (the encapsulation function of movement)
            // Suitable for accelerated movement
            // So we can't directly use the encapsulation function of motion. We need to rewrite it
            
            // Calculate random step size
            var speedX = random(-10,10);
            var speedY = random(-20,0);
            // Start timer
            this.f.t = setInterval(() => {
                // Because it's a free fall, judge whether the element exceeds the big box
                if(this.f.offsetTop > this.cont.offsetHeight){
                    // Over, clear the timer and delete the corresponding fireworks
                    clearInterval(this.f.t);
                    this.f.remove();
                }else{
                    // No more than, normally move according to step size
                    this.f.style.left = this.f.offsetLeft + speedX + "px";
                    // In the process, the step size of Y is increased continuously, resulting in the acceleration effect of gravity
                    this.f.style.top = this.f.offsetTop + speedY++ + "px";
                }
            }, 30);
            }
          }

In this way, we can realize the part of our fireworks. Let's show you the effect first

Now I want to give you all the code. You can understand well according to the steps I wrote, when to create what content, transfer what information, or remove what instances.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#container{
				width: 80%;
				height: 600px;
				margin: 20px auto;
				background: black;
				border: 2px solid red;
				/*Make a relative position for fireworks*/
				position: relative;
				cursor: pointer;
				/*When the fireworks explode beyond the black screen, the overlay does not display*/
				overflow: hidden;
				
			}
			.fire{
				width: 10px;
				height: 10px;
				position: absolute;
				/*Let the theme fireworks be initially positioned at the bottom of the black frame to pave the sky behind*/
				bottom: 0;
			}
			.small-fire{
				width: 10px;
				height: 10px;
				/*Set to circle*/
				border-radius:50%;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="container"></div>
	</body>
	<script type="text/javascript">
//		1, Theme fireworks
		class Fire{
//			1. Constructor
			constructor(pos){
//				2. Get the black box element
				this.cont = document.getElementById("container");
//              5. Since the coordinates are passed to the new method, the constructor is responsible for receiving (receiving an object)
//                After receiving the object, directly parse the key value pair in it to this, which is convenient for use in subsequent methods
                 this.x = pos.x;
                 this.y = pos.y
			}
//			3. Create theme fireworks
			create(){
//				3.1 create theme fireworks this.f
				this.f = document.createElement("div");
//				3.2 get its style
				this.f.className = "fire";
//				3.3 random colors by color random function
                this.f.style.background = randomColor();
//				3.4 assign it to a black box
                this.cont.appendChild(this.f);
//              5. The display position of fireworks is the position of the x axis corresponding to the mouse click
                this.f.style.left = this.x + "px";
//              7. Let it move after creation
                this.fireMove();
				
			}
//			6. Let the theme fireworks rise to the height of our mouse click
//           The first parameter of the motion encapsulation function is the element, the second is the required motion attribute and the target position, and the third is the new function
              fireMove(){
              	move2(this.f,{
              		top:this.y,
              	},()=>{
//            		It is just analyzed that after the theme fireworks are moved, they should disappear to show the effect of small fireworks exploding
//                  8. Remove the subject fireworks instance
                    this.f.remove();
//                  9. Prepare a small fireworks instance and randomly set the number (between 10 and 20) (because it takes many to explode)
                    var randomNum = random(10,20);
//                  10. At the same time of creating a small fireworks instance, pass the required information to facilitate use
                    for(var i = 0; i<randomNum;i++){
//                  	Pass information on
                    	var sf = new smallFire({
//                  		cont: black box, x:left distance (coordinate), y:top distance (coordinate)
                    		cont:this.cont,
                    		x:this.x,
                    		y:this.y
                    	})
//                  	11. And create methods for its execution
                    	sf.create();
                    }

              	})
              }
		}
//		2, Fireworks
          class smallFire{
//        	12. By accepting the parameters and analyzing the object, get the required information for easy use
          	constructor(obj){
            this.cont = obj.cont;
            this.x = obj.x;
            this.y = obj.y;
        }
//        	13. Creation of fireworks
          	create(){
//          13.1 create the elements of the fireworks, get the style, and get its coordinates.
            this.f = document.createElement("div");
            this.f.className = "small-fire";
            this.f.style.background = randomColor();
            this.cont.appendChild(this.f);
            this.f.style.left = this.x + "px";
            this.f.style.top = this.y + "px";
//          15. Let it move directly after creation
            this.smallMove();
          	}
//        	14. Movement of small fireworks
            smallMove(){
            // Because of the free falling effect, the movement of fireworks is not suitable to use the buffering movement (the encapsulation function of movement)
            // Suitable for accelerated movement
            // So we can't directly use the encapsulation function of motion. We need to rewrite it
            
            // Calculate random step size
            var speedX = random(-10,10);
            var speedY = random(-20,0);
            // Start timer
            this.f.t = setInterval(() => {
                // Because it's a free fall, judge whether the element exceeds the big box
                if(this.f.offsetTop > this.cont.offsetHeight){
                    // Over, clear the timer and delete the corresponding fireworks
                    clearInterval(this.f.t);
                    this.f.remove();
                }else{
                    // No more than, normally move according to step size
                    this.f.style.left = this.f.offsetLeft + speedX + "px";
                    // In the process, the step size of Y is increased continuously, resulting in the acceleration effect of gravity
                    this.f.style.top = this.f.offsetTop + speedY++ + "px";
                }
            }, 30);
            }
          }
//		4.
		var ocont = document.getElementById("container");
		ocont.onclick = function(eve){
//			4.1 define event objects
			var e = eve||event;
//			4.2 get coordinates to prepare for fireworks (coordinate range generated by theme fireworks)
			var x = e.pageX - this.offsetLeft;
			var y = e.pageY - this.offsetTop;
//			4.3 create a fireworks element, and transfer the above coordinates to the past through parameter transfer, which is convenient for use
			var f = new Fire({
				x:x,
				y:y
			});
//			4.4 execute the method of creating fireworks
			f.create();
		}
		
		
		
		
//	Random number encapsulation function	
	function random(min, max) {
    return Math.round(Math.random()*(max - min)+min);
 }	
//	Random color value encapsulation function	
	function randomColor(){
        return `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`;
    }
//	Encapsulation function of motion process
	function move2(ele,obj,cb){
    clearInterval(ele.t);
    ele.t = setInterval(() => {
        // Assume the status is: timer can be cleared
        var i = true;
        // Because the information in the object is only used in the timer, it is traversed in the timer
        // Properties and target variables exchanged in advance
        for(var attr in obj){
            if(attr == "opacity"){
                var iNow = getStyle(ele,attr) * 100;
            }else{
                var iNow = parseInt(getStyle(ele,attr));
            }
    
            let speed = (obj[attr] - iNow)/10;
            speed = speed < 0 ? Math.floor(speed) : Math.ceil(speed);
            // As long as there's one attribute to the target, it stops, right
            // All attributes must be to the target to stop

            // As long as there's one attribute that doesn't reach the target, it can't be stopped
                // Use status to mark whether to stop the timer or not

            // As long as one attribute fails to reach the target: never clear the timer
            if(iNow !== obj[attr]){
                i = false;
            }
            if(attr == "opacity"){
                ele.style.opacity = (iNow + speed)/100;
            }else{
                ele.style[attr] = iNow + speed + "px";
            }
        }
            // If all attributes are executed once at the end of each timer, the status is still true, indicating that they have not been changed to false. If they have not been changed to false, indicating that no attribute has not reached the end point, then the status is still false and will not be cleared
        if(i){
            clearInterval(ele.t);
            // The user decides the function to be executed at the end of the animation. If the user does not pass parameters, make a default judgment
            if(cb){
                cb();
            }
            // cb && cb();
        }
    }, 30);
}
// Get the compatibility of non inline styles: you must get the current style value (get the style encapsulation function)
function getStyle(ele,attr){
        if(ele.currentStyle){
            return ele.currentStyle[attr];
        }else{
            return getComputedStyle(ele,false)[attr];
        }
    }
	</script>
</html>

Published 4 original articles, won praise 2, visited 59
Private letter follow

Topics: Attribute Javascript