Fireworks Animation Using HTML, CSS & JS
Stelvin Saji
?? Author of Expressive Emojis ???. Curator of 'Smart Coding' with 55K+ subscribers ????. Front-end developer crafting responsive designs with JavaScript ??. Using React & Redux ????, Firebase ??, and Tailwind CSS ????.
So in this article, we're gonna make a Fireworks animation with canvas using HTML, CSS & JS. So let's start writing some code!
We are gonna start by writing basic?HTML?& then style it using?CSS?& at last implement?JS.
HTML Code :
First, we are gonna create a Boilerplate for the?HTML?Code & link it with the?CSS?&?JS?files.
Inside the body, we're gonna add a?canvas tag. After that, we're gonna link the?JS file?below.
The output of the?HTML?code :
The output will just print a blank page.
Now let's add some?CSS?to style the page.
CSS Code :
Inside the CSS file, we're gonna target the canvas element and inside that, we're gonna set the position of the element relative to its parent container. The "top" property sets the distance from the top edge of the parent container to the top edge of the element, and the "left" sets the distance from the left edge of the parent container to the left edge of the element.
In this case, both "top" and "left" are set to 0 pixels, meaning that the top-left corner of the element will be aligned with the top-left corner of the parent container.
The "position" property in CSS determines how an element is positioned within the web page layout. When the "position" property is set to "absolute", the element is positioned relative to the nearest positioned ancestor element, or to the body element if there is no positioned ancestor.
An element with an "absolute" position is taken out of the normal document flow, and it can be positioned anywhere on the page by setting the "top", "bottom", "left", and "right" properties. The "top" and "left" properties are set to 0 pixels, so the element will be positioned at the top-left corner of the parent container.
The "width" and "height" properties set the size of the element in CSS. In this case, both properties are set to 100%, which means that the element will have the same width and height as the parent container.
Setting the width and height of an element to 100% can be useful when you want the element to take up the full size of the parent container, regardless of its content size.
In this case, the canvas element will cover the entire parent container, so you can use the canvas to display graphics, animations, or other content.
The "box-sizing" property in CSS determines how the size of an element is calculated, including any padding and borders that are added to the element.
When the "box-sizing" property is set to "border-box", the width and height of the element include any padding and borders that are added to the element. This means that the element will be the exact size specified by the width and height properties, even if padding or borders are added.
The "box-sizing" property is set to "border-box", which means that the canvas element will have the specified width and height, including any padding and borders that may be added. This can be useful if you want to ensure that the canvas takes up a specific amount of space on the page, even if padding or borders are added.
The output of the CSS code :
Again, the output will print a blank page.
Now let,s add some JS to make the animation. Once the user clicks on the screen, the animation may appear. So let's work on that now.
JS Code :
Now inside the JS file, we're gonna select the canvas element(which was in the HTML file) and then obtain its 2D rendering context.
Then we're gonna create an array of particles and sets the initial number of particles to 400. It also creates an object to store the mouse position.
We can use it as a starting point for creating a particle system that interacts with the mouse position. For example, we can use the mouse position to control the behavior of the particles, such as their attraction or repulsion.
Then we're gonna set the value of angle, gravity, and friction.
领英推荐
This array can be used to store color codes or color values, which can be used to assign a specific color to each particle in a particle system. The color values can be represented in various formats, such as RGB (red, green, blue) or HEX (hexadecimal) values. The color values stored in this array can be used to set the fill or stroke style of each particle, giving each particle its own unique color.
Then we're gonna create a function called pickAColor which will return random color from the colorCode array.
The function uses the following steps to generate a random color:
This function can be called multiple times to randomly select a color from the colorCode array, and the result can be used to set the color of objects or elements in a particle system, creating a more visually interesting and varied display.
Then we're gonna add event listeners to the canvas to respond to different events such as resizing the window, moving the mouse, and clicking the mouse.
The line addEventListener("resize", (e) => {...}) sets up an event listener on the canvas that listens for a resize event. When the resize event is triggered (i.e. when the size of the window changes), the event listener will be triggered and the code inside the arrow function will be executed.
The code inside the arrow function updates the size of the canvas by setting cvs.width to window.innerWidth and cvs.height to window.innerHeight. This ensures that the canvas always matches the size of the window so that the entire particle system will be visible at all times.
Then next line addEventListener("mousemove", (e) => {...}) sets up an event listener on the canvas that listens for a mousemove event. When the mousemove event is triggered (i.e. when the mouse is moved), the event listener will be triggered and the code inside the arrow function will be executed.
The code inside the arrow function updates the mouse object with the current x and y coordinates of the mouse. The x coordinate is given by e.clientX, and the y coordinate is given by e.clientY. This information can be used in other parts of the code to affect the behavior of the particles based on the position of the mouse.
For example, you could use the mouse position to change the direction of the particles, attract or repel particles towards or away from the mouse, or even change the size or color of the particles based on the position of the mouse.
The last one addEventListener("mousedown", (e) => {...}) sets up an event listener on the canvas that listens for a mousedown event. When the mousedown event is triggered (i.e. when the mouse button is clicked), the event listener will be triggered and the code inside the arrow function will be executed.
The code inside the arrow function calls the init function. The init function is likely used to initialize the particle system, such as setting up the initial positions, velocities, and other properties of the particles.
By calling init in response to a mouse click, you can allow the user to reset the particle system or change its configuration dynamically. This makes the particle system more interactive and allows the user to experiment with different configurations to see how they affect the appearance of the particles.
Then we're gonna define a class named Particles that represents a single particle in the particle system. The Particles class has several properties and methods that define its behavior and appearance.
The constructor function takes two arguments: x and y, which represent the initial x and y coordinates of the particle, and spin, which represents the initial velocity of the particle. The constructor sets the following properties:
The draw method is used to render the particle on the canvas. It sets the global alpha value to the particle's alpha property and draws a filled circle using the canvas API.
The update method is used to update the properties of the particle for each frame of the animation. It first multiplies the x and y components of the spin property by the friction value to slow down the particle over time. Then it adds the gravity value to the y component of spin to simulate the effect of gravity. Finally, it adds the x and y components of spin to the x and y coordinates of the particle to update its position. The alpha property of the particle is also decremented by 0.002 to make it gradually disappear over time.
The Particles class provides a convenient way to encapsulate the properties and behavior of a single particle, making it easier to manage and update the particle system as a whole.
Then we're gonna create a function that initializes an array of particles with a given number of elements, noOfParticles. For each particle, it creates a new instance of the Particles object and pushes it onto the particleArray. The x and y properties of each particle are set to a random value that's proportional to the cosine and sine of the current angle, angle * i.
The Particles constructor takes three arguments: the x and y position of the particle and an object literal that describes the velocity of the particle in the x and y direction.
The Math.cos and Math.sin functions are used to calculate the horizontal and vertical velocity components of the particle. The angle * i term gives each particle a unique velocity direction, while the Math.random() * 5 term adds some randomness to the magnitude of the velocity.
Then we're gonna create another function that implements the animation loop for the particles. It first fills the canvas with a translucent black color to create a fade-out effect. This is done using the fillStyle and fillRect properties of the 2D rendering context, ctx.
Next, it calls requestAnimationFrame(animate) to request the browser to call the animate function again on the next frame. This creates an animation loop that updates the particles on each frame.
The particleArray is then iterated over using the forEach method. For each particle in the array, the draw and update methods of the particle are called. The draw method is responsible for rendering the particle on the canvas, while the update method updates the position and velocity of the particle.
If a particle's alpha value becomes 0, it is removed from the particleArray using the splice method. This ensures that the particle is only drawn and updated while it's still visible.
Lastly, we're gonna start the animation by calling the animate function. The animate function will then continuously run, updating the position and rendering of the particles in the particleArray on each frame.
This creates the desired animation effect.
M.Tech.CSE specialization in (AI&ML) VIT-V |Ex-L&T Technology Services | Python, ML, Embedded C, Cpp, Zephyr RTOS, Embedded Peripherals | B.Tech.(DSU)
1 年@nu u hymn mkm lookin
Thanks for the cool article! I didn't even realize that the preview is an actual screenshot of the result -- it looks amazing. I'd suggest to add a GIF animation to the very beginning of the article, if it's possible and place the vercel link there as well. I think this might help to catch attentions) Awesome stuff!