js to achieve cool fireworks effect

js to achieve cool fireworks effect

This article shares the specific code for using js to achieve cool fireworks effects for your reference. The specific content is as follows

We need to clarify the thinking of the entire process.

First, create a canvas to display the effect of fireworks, and then think about the process of fireworks. We all know that fireworks usually fly into the sky first, and then disperse into many small fireworks, and each small firework has a different style and movement.

The overall idea is to first create a div as our big firework. When the big firework moves to the position where our mouse is clicked, the big firework will disappear, and then more small fireworks will be generated, and the movement trajectory styles of these small fireworks are different.

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

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

2. Get the node

 //Get the node var app = document.getElementById('container');
        //Set a binding event for app 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)
            }

The process of realizing fireworks: first realize a large div moving to the position where the mouse is clicked, and then spread out into many divs

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

// Constructor function Fire(app, pos) {
            //Set the property to the variable this.app = app;
            this.pos = pos;
            // Create a large div
            this.bf = document.createElement('div');
            //Set a class name this.bf.className = 'fire';
            //Set style this.bf.style.left = this.pos.cx + 'px';
            this.bf.style.background = this.getColor();
            this.app.appendChild(this.bf);
            //Call the motion function this.move(this.bf, {
                top: this.pos.cy
            }, () => {
                this.bf.remove();
                this.smallFire();
            })
        }

3.1 First set the style of fire

This is the initial style of fire

 .fire {
        background: red;
        position: absolute;
        /* When setting bottom, top is obtained as the maximum value, minus the mouse click position*/
        bottom: 0px;
        width: 6px;
        height: 6px;
    }

3.2 Method to set a random number and random color (prototype object)

//Get a random number method Fire.prototype.rand = function(min, max) {
            return Math.round(Math.random() * (max - min) + min);
        }
 
 
//Method to get a random color 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 the movement for (let attr in target) {
                        // attr represents the attribute of the movement // console.log(attr);
                        // Get the real-time value of the element attribute let tmpVal = parseInt(this.getPos(ele, attr))
                            // Calculate speed
                            // console.log(tmpVal, attr);
                        let speed = (target[attr] - tmpVal) / 10;
                        // Round speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                        // Stop the timer, when an attribute moves to position, set the switch state if (tmpVal == target[attr]) onOff = true;
                        // Make the element move ele.style[attr] = tmpVal + speed + 'px';
                    }
 
                    // Determine the switch status and clear the timer for (var moveAttr in target) {
                        // If they are not equal, it means that some attributes have not moved to the position and the timer cannot be stopped if (target[moveAttr] !== parseInt(this.getPos(ele, moveAttr))) {
                            onOff = false;
                            break;
                        }
                    }
                    if (onOff) {
                        clearInterval(times);
                        cb && cb();
                    }
                    // console.log(1111);
                }.bind(this), 30)
            }
            // Function to get the real-time position of an element Fire.prototype.getPos = function(obj, attr) {
            if (obj.currentStyle) { // Get the CSS style return obj.currentStyle[attr];
            } else {
                return getComputedStyle(obj)[attr]
            }
        }

Through the above steps, we can get the movement trajectory of the big fireworks. After the big fireworks move to the specified position, they will disappear, and many small fireworks will be generated from the place where they disappear. From the previous analysis, we can know that the movement trajectories and styles of small fireworks are different. The next step is to realize small fireworks.

4. Implementation of small fireworks

4.1 Setting the style of samll-fire

This is the initial property of samll-fire

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

4.2 Set the properties of small fireworks

//Small fireworks Fire.prototype.smallFire = function() {
            //First, we set the number of small fireworks let num = this.rand(50, 60)
            //Traverse and set different styles for each small firework 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 trajectory of the small fireworks into a circular motion//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 the small firework a random position, which can be any position in the canvas let top = this.rand(0, this.app.offsetHeight - sf.offsetHeight);
                 let left = this.rand(0, this.app.offsetWidth - sf.offsetWidth);
                //Call the motion function this.move(sf, {
                    top: top,
                    left: left
                }, function() {
                    sf.remove();
                })
            }
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • js simulation to achieve fireworks effects
  • Native JS to achieve fireworks effect
  • Very beautiful js fireworks effect
  • js to achieve click fireworks effect
  • JavaScript to achieve fireworks effects (object-oriented)
  • JavaScript implements fireworks effects with sound effects
  • JavaScript implements five different fireworks effects

<<:  mysql uses stored procedures to implement tree node acquisition method

>>:  Modification of time zone problem of MySQL container in Docker

Recommend

Detailed explanation of MySQL binlog usage

binlog is a binary log file that records all DML ...

Detailed explanation of cross-usage of Ref in React

Table of contents 1. First, let’s explain what Re...

In-depth understanding of MySQL master-slave replication thread state transition

Preface The basic principle of MySQL master-slave...

HTML+css to create a simple progress bar

1. HTML code Copy code The code is as follows: Ex...

How to monitor Windows performance on Zabbix

Background Information I've been rereading so...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...

uni-app implements NFC reading function

This article shares the specific code of uni-app ...

Implementation of drawing audio waveform with wavesurfer.js

1. View the renderings Select forward: Select bac...

Ubuntu Docker installation in vmware (container building)

1. Mind Map 2. How to build a container 2.1 Prepa...

Native JS to achieve digital table special effects

This article shares a digital clock effect implem...

Tutorial on resetting the root password of Mac MySQL

Disclaimer: This password reset method can direct...

How to Completely Clean Your Docker Data

Table of contents Prune regularly Mirror Eviction...

A brief summary of basic web page performance optimization rules

Some optimization rules for browser web pages Pag...

How to import and export Cookies and Favorites in FireFox

FireFox is a commonly used browser with many exte...