国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Browser support
Desktop
Mobile/tablet
HTML structure
CSS Style
JavaScript Code
Step 1: Click the Event
Step 2: Particle Creation
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>

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 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);
}

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!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

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)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

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.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

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

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

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

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

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

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

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.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

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

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

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.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

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

See all articles