Table of Contents
Browser support
Desktop
Mobile/tablet
HTML structure
CSS Style
JavaScript Code
Step 1: Click the Event
Step 2: Particle Creation
Step 3: Particle Width, Height, and Background
Step 4: Animate each particle
Step 5: Remove particles after the animation is completed
Final effect
Unlimited creativity
Home Web Front-end CSS Tutorial Playing With Particles Using the Web Animations API

Playing With Particles Using the Web Animations API

Apr 09, 2025 am 09:25 AM

Use the Web Animations API to create cool particle effects: click the button to bloom fireworks!

Playing With Particles Using the Web Animations API

Nothing can show the charm of animation better than particle effects! Every time I explore a new technology, I can’t help but use as many particles as possible to make a presentation. This article will use the Web Animations API to trigger firework effects by clicking a button to create more amazing particle magic.

Browser support

As of the time of writing, all major browsers, except Safari and Internet Explorer, support the Web Animations API at least in part. Safari support can be enabled in the "Experience Features" developer menu.

The browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature from this version and later.

Desktop

Mobile/tablet

If you want to reproduce Twitter love animation, you can also refer to this wonderful article by Ana Tudor, which is also a great example of the effect of a button explosion particle.

HTML structure

This demo doesn't require much HTML code. We will use one<button></button> Element, but can also be other types of tag elements. If needed, we can even listen to any click event on the page to let the particles pop up from anywhere.

 <button id="button">Click me</button>
Copy after login

CSS Style

Since each particle has some common CSS properties, we can set them in the global CSS of the page. You can create custom tag elements like in HTML, I will use<particle></particle> Tag names to avoid using semantic tags. But in fact, you can animation<div> ,<code><span></span> or any label you choose.

 particle {
  border-radius: 50%;
  left: 0;
  pointer-events: none;
  position: fixed;
  top: 0;
  opacity: 0; /*The initial transparency is 0, avoiding particles visible before the animation starts*/
}
Copy after login

What should be noted is:

  • Particles should not interact with the layout of the page, so we set position to fixed , top and left to 0px.
  • We also removed pointer-events to avoid any user interaction with HTML particles when they appear on the screen.

Since the style design of button and page layouts is not the focus of this article, I will skip this section.

JavaScript Code

Here are six steps we will follow in JavaScript:

  1. Listen to the click event of the button
  2. Create 30<particle></particle> and add the element to the DOM
  3. Set random width, height, and background color for each particle
  4. Animate each particle so it moves from mouse position to random position and fades out gradually
  5. After the animation is completed, remove it from the DOM<particle></particle> element

Step 1: Click the Event

 // We first check whether the browser supports the Web Animations API
if (document.body.animate) {
  // If supported, we add a click listener document.querySelector('#button').addEventListener('click', pop);
}
Copy after login

Step 2: Particle Creation

 // The pop() function is called function pop(e) {
  // Circularly generate 30 particles for (let i = 0; i <h4 id="Step-Particle-Width-Height-and-Background"> Step 3: Particle Width, Height, and Background</h4><pre class="brush:php;toolbar:false"> function createParticle(x, y) {
  // ... (Previous code)
  // Calculate the random size between 5px and 25px const size = Math.floor(Math.random() * 20 5);
  // Apply size to each particle.style.width = `${size}px`;
  partial.style.height = `${size}px`;
  // Generate random colors in the blue/purple palette partial.style.background = `hsl(${Math.random() * 90 180}, 70%, 60%)`;
  // ... (Next steps)
}
Copy after login

Step 4: Animate each particle

 function createParticle(x, y) {
  // ... (Previous code)
  // Generate random x and y target positions in the range of mouse position 75px 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 initial position of the particle// We use half the size of the particle to shift the particle so that it is centered on the mouse: `translate(${x - (size / 2)}px, ${y - (size / 2)}px)`,
      opacity: 1
    },
    {
      // We define the final coordinate as the second keyframe transform: `translate(${destinationX}px, ${destinationY}px)`,
      opacity: 0
    }
  ], {
    // Set the random duration between 500ms and 1500ms: 500 Math.random() * 1000,
    easing: 'cubic-bezier(0, .9, .57, 1)',
    // Use random values ​​between 0ms and 200ms to delay each particle: Math.random() * 200
  });
  // ... (Next steps)
}
Copy after login

Step 5: Remove particles after the animation is completed

 function createParticle(x, y) {
  // ... (Previous code)
  // When the animation is complete, remove the element animation.onfinish from the DOM = () => {
    particle.remove();
  };
}
Copy after login

Final effect

By integrating all the code together, we can get the effect we want: colorful particle explosion effect.

If you do not see animations in the demo, please check whether your browser supports the Web Animations API. For details, please refer to the browser support form at the beginning of the article.

Unlimited creativity

Since all of this uses CSS, modifying the particle style is very simple. Here are some examples using various shapes (even characters!).

Or we can even let the button itself explode like Zach Saucier did in this post.

(Second additional example code for other shapes and characters and links to Zach Saucier article)

The above is the detailed content of Playing With Particles Using the Web Animations API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Creating Your Own Bragdoc With Eleventy Creating Your Own Bragdoc With Eleventy Mar 18, 2025 am 11:23 AM

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

See all articles