Louis Hoebregts writing for CSS-Tricks
When it comes to motion and animations, there is probably nothing I love more than particles. This is why every time I explore new technologies I always end up creating demos with as many particles as I can.
In this post, we’ll make even more particle magic using the Web Animations API to create a firework effect when clicking on a button.
At its core site this createParticle
function
function createParticle (x, y) {
// [...]
// Generate a random x & y destination within a distance of 75px from the mouse
const destinationX = x + (Math.random() - 0.5) * 2 * 75;
const destinationY = y + (Math.random() - 0.5) * 2 * 75;
// Store the animation in a variable because we will need it later
const animation = particle.animate([
{
// Set the origin position of the particle
// We offset the particle with half its size to center it around the mouse
transform: `translate(${x - (size / 2)}px, ${y - (size / 2)}px)`,
opacity: 1
},
{
// We define the final coordinates as the second keyframe
transform: `translate(${destinationX}px, ${destinationY}px)`,
opacity: 0
}
], {
// Set a random duration from 500 to 1500ms
duration: 500 + Math.random() * 1000,
easing: 'cubic-bezier(0, .9, .57, 1)',
// Delay every particle with a random value from 0ms to 200ms
delay: Math.random() * 200
});
}