Use the Web Animations API to create cool particle effects: click the button to bloom fireworks!
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>
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*/ }
What should be noted is:
- Particles should not interact with the layout of the page, so we set
position
tofixed
,top
andleft
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:
- Listen to the click event of the button
- Create 30
<particle></particle>
and add the element to the DOM - Set random width, height, and background color for each particle
- Animate each particle so it moves from mouse position to random position and fades out gradually
- 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); }
Step 2: Particle Creation
// The pop() function is called function pop(e) { // Circularly generate 30 particles for (let i = 0; i <h4> 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) }
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) }
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(); }; }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
