Mouse Cursor Confetti (GSAP Physics2D)
Documentation
Webflow
Code
Setup: External Scripts
HTML
<script src="https://cdn.jsdelivr.net/npm/gsap@3.15/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.15/dist/Physics2DPlugin.min.js"></script>Step 1: Add HTML
HTML structure is not required for this resource.
Step 2: Add CSS
CSS
body {
overflow: clip;
}
.dot {
position: absolute;
background-color: #D3DCCD;
width: 1rem;
height: 1rem;
border-radius: 50%;
will-change: transform, opacity;
pointer-events: none;
}Step 2: Add Javascript
Step 3: Add Javascript
Javascript
gsap.registerPlugin(Physics2DPlugin);
document.addEventListener("click", (event) => {
// Generate a random number of dots (3 to 10)
const dotCount = gsap.utils.random(3, 10, 1);
const colors = ["#D3DCCD", "#F5FEEF", "#6C7E5F", "#818A7B", "#94A787"]; // Define colors once
for (let i = 0; i < dotCount; i++) {
// Create a dot element
const dot = document.createElement("div");
dot.classList.add("dot");
// Append the dot to the body
document.body.appendChild(dot);
// Set initial position and styles of the dot
gsap.set(dot, {
backgroundColor: gsap.utils.random(colors), // Pick a random color
top: event.clientY, // position dot at coordinates of the click
left: event.clientX,
scale: 0, // Start at scale 0
});
// Animate the dot with physics2D
gsap.timeline({
onComplete: () => dot.remove(), // Remove the dot after animation
})
.to(dot, {
scale: gsap.utils.random(0.5, 1), // Scale between 0.5 and 1
duration: 0.3, // Quick pop-in effect
ease: "power3.out",
})
.to(dot, {
duration: 2,
physics2D: {
velocity: gsap.utils.random(200, 650), // Random velocity
angle: gsap.utils.random(0, 360), // Random direction
gravity: 500, // Gravity effect
},
autoAlpha: 0, // Fade out towards the end
ease: "none",
}, "<"); // Start together with the previous tween
}
});Implementation
Customization
The Physics2D plugin from GSAP serves as a way to easily create interesting physics-based effects. We highly recommend diving into their documentation page to discover all of the possibilities. In our example we paired it with several random functions to make the animation as dynamic as possible.
Inspiration
Checkout the Fruitful website, where Ilja paired the mouse click animation with the generation of a random Lottie file to create a unique and on-brand experience. Or play around with the main 'get GSAP' button on the GSAP Homepage, where the Physics2D plugin was used to create a fun animation on button hover.
Resource details
Published
December 28, 2024
Category
Gimmicks
Popularity
655 visitors
Need help?
Join Slack