js achieves cool fireworks effect

  • 2021-11-14 04:42:16
  • OfStack

In this paper, we share the specific code of js to achieve cool fireworks effect for your reference. The specific contents are as follows

We need to clarify the thinking of the whole process.

First, build a canvas to show the effect of fireworks, and then think about the process of fireworks discharge. We all know that fireworks usually fly to the sky first, and then disperse into many small fireworks, and each small fireworks has different styles and movements.

All the overall idea is to build an div as our big fireworks first. When the big fireworks move to the position where we click with the mouse, the big fireworks will disappear, and then more small fireworks will be produced, and the movement track styles of these small fireworks are different.

1. Create a canvas (div) to show the effect of fireworks


/* Set the canvas css Style   */
#container {
        width: 80%;
        height: 600px;
        border: 1px red solid;
        position: relative;
        margin: 20px auto;
        cursor: pointer;
        background: black;
    }
<!--  Settings 1 A div -->
<div id="container"></div>

2. Get the node


 // Get Node 
 var app = document.getElementById('container');
        // To app Settings 1 Binding events 
        app.onclick = function(event) {
                var e = event || window.event
               // Get the coordinates of the mouse click position 
                var pos = {
                    cy: e.offsetY,
                    cx: e.offsetX
                }
                new Fire(app, pos)
            }

Fireworks realization process: First realize a large div movement to the mouse click position, and then spread out into many div

3. Realize big fireworks first (need to call random number method, random color method and motion function)


//  Constructor 
function Fire(app, pos) {
            // Set the property as a variable 
            this.app = app;
            this.pos = pos;
            // Create 1 A big one div
            this.bf = document.createElement('div');
            // Settings 1 Class name 
            this.bf.className = 'fire';
            // Setting Styles 
            this.bf.style.left = this.pos.cx + 'px';
            this.bf.style.background = this.getColor();
            this.app.appendChild(this.bf);
            // Call motion function 
            this.move(this.bf, {
                top: this.pos.cy
            }, () => {
                this.bf.remove();
                this.smallFire();
            })
        }

3.1 Style fire first

This is the initial style of fire


 .fire {
        background: red;
        position: absolute;
        /*  Settings bottom Hour ,top Get to the maximum value , Subtract the mouse click position  */
        bottom: 0px;
        width: 6px;
        height: 6px;
    }

3.2 Method for Setting 1 Random Number and Random Color (Prototype Object)


// Obtain 1 Random number method 
Fire.prototype.rand = function(min, max) {
            return Math.round(Math.random() * (max - min) + min);
        }
 
 
// Obtain 1 Method of random colors 
 Fire.prototype.getColor = function() {
         let sum = '#';
         for (let i = 0; i < 6; i++) {
               sum += this.rand(0, 15).toString(16)
           }
             return sum;
           }

3.3 Encapsulate a motion function (prototype object)


Fire.prototype.move = function(ele, target, cb) {
                // clearInterval(times);
                let times = setInterval(function() {
                    // console.log(this);
                    var onOff = true;
                    //  Traverse the direction and target of motion 
                    for (let attr in target) {
                        // attr  Attributes representing motion 
                        // console.log(attr);
                        //  Gets the real-time value of an element attribute 
                        let tmpVal = parseInt(this.getPos(ele, attr))
                            //  Calculation speed
                            // console.log(tmpVal, attr);
                        let speed = (target[attr] - tmpVal) / 10;
                        //  Rounding 
                        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                        //  Stop timer , When 1 Attributes move to position , Set the switch state 
                        if (tmpVal == target[attr]) onOff = true;
                        //  Let the elements move 
                        ele.style[attr] = tmpVal + speed + 'px';
                    }
 
                    //  Judge the switch state , Clear timer 
                    for (var moveAttr in target) {
                        //  If not equal , It means that there are attributes that have not moved to the position , The timer cannot stop 
                        if (target[moveAttr] !== parseInt(this.getPos(ele, moveAttr))) {
                            onOff = false;
                            break;
                        }
                    }
                    if (onOff) {
                        clearInterval(times);
                        cb && cb();
                    }
                    // console.log(1111);
                }.bind(this), 30)
            }
            //  A function that gets the real-time position of an element 
        Fire.prototype.getPos = function(obj, attr) {
            if (obj.currentStyle) { //  Get css Style of 
                return obj.currentStyle[attr];
            } else {
                return getComputedStyle(obj)[attr]
            }
        }

Through the above steps, we can get the trajectory of the big fireworks. After the big fireworks move to the designated position, they will disappear, and many small fireworks will be produced from the disappeared place. From the previous analysis, we can know that the movement track and style of small fireworks are different, and the next step is the realization of small fireworks

4. The realization of small fireworks

4.1 Styling samll-fire

This is the initial property of samll-fire


.small-fire {
        width: 10px;
        height: 10px;
        position: absolute;
        border-radius: 50%;
    }

4.2 Setting Small Fireworks Properties


// Small fireworks 
Fire.prototype.smallFire = function() {
            // First, we set the number of small fireworks 
            let num = this.rand(50, 60)
            // Traversal   To each 1 Set different styles for small fireworks 
            for (let i = 0; i < num; i++) {
                let sf = document.createElement('div');
                sf.className = 'small-fire';
                sf.style.left = this.pos.cx + 'px';
                sf.style.top = this.pos.cy + 'px';
                sf.style.background = this.getColor();
                //console.log(sf);
                // Append to the page 
                this.app.appendChild(sf);
                // Make the motion track of small fireworks move in a circle 
                //var top = parseInt(Math.sin(Math.PI / 180 * 360 / num * i) * r) + this.pos.cy;
                //var left = parseInt(Math.cos(Math.PI / 180 * 360 / num * i) * r) + this.pos.cx;
                 // Give small fireworks 1 Random position, which can be any place in the canvas 1 Position 
                 let top = this.rand(0, this.app.offsetHeight - sf.offsetHeight);
                 let left = this.rand(0, this.app.offsetWidth - sf.offsetWidth);
                // Call motion function 
                this.move(sf, {
                    top: top,
                    left: left
                }, function() {
                    sf.remove();
                })
            }
}

Related articles: