Sure! Below is a complete HTML file that captures click events, places a random number of emojis at the click position, and applies gravity and collision effects to each emoji. The emojis will fall down with gravity and bounce when they hit the bottom of the viewport.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Emoji Gravity and Collision</title>
<style>
body {
margin: 0;
overflow: hidden;
position: relative;
height: 100vh;
background-color: #f0f0f0;
cursor: pointer;
}
.emoji {
position: absolute;
font-size: 24px;
user-select: none;
pointer-events: none;
will-change: transform;
}
</style>
</head>
<body>
<script>
// List of emojis to choose from
const emojiList = ['😀', '😂', '😍', '🔥', '✨', '🍀', '🌟', '❤️', '🎉', '🍕', '🚀', '🐱👤'];
// Array to hold all emoji objects
const emojis = [];
// Gravity acceleration (pixels per second squared)
const GRAVITY = 980; // Adjust as needed
// Time of the last frame
let lastTime = null;
// Emoji class to handle individual emoji properties and behavior
class Emoji {
constructor(element, x, y) {
this.element = element;
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * 200; // Horizontal velocity: random between -100 and 100 px/s
this.vy = 0; // Initial vertical velocity
this.radius = 12; // Approximate radius based on font-size
this.bounceFactor = 0.7; // Energy retained after bounce
}
update(deltaTime) {
// Update velocity with gravity
this.vy += GRAVITY * deltaTime;
// Update position with velocity
this.x += this.vx * deltaTime;
this.y += this.vy * deltaTime;
// Collision with the floor
const floor = window.innerHeight - this.radius;
if (this.y > floor) {
this.y = floor;
this.vy *= -this.bounceFactor;
// Optional: Slow down horizontal movement due to friction
this.vx *= this.bounceFactor;
}
// Collision with the walls
const left = this.radius;
const right = window.innerWidth - this.radius;
if (this.x < left) {
this.x = left;
this.vx *= -this.bounceFactor;
} else if (this.x > right) {
this.x = right;
this.vx *= -this.bounceFactor;
}
// Update the position of the emoji element
this.element.style.transform = `translate3d(${this.x}px, ${this.y}px, 0)`;
}
}
// Handle click events
document.body.addEventListener('click', function(event) {
const numEmojis = Math.floor(Math.random() * 5) + 1; // Random between 1 and 5
for (let i = 0; i < numEmojis; i++) {
const emojiChar = emojiList[Math.floor(Math.random() * emojiList.length)];
const emojiElement = document.createElement('div');
emojiElement.classList.add('emoji');
emojiElement.textContent = emojiChar;
document.body.appendChild(emojiElement);
// Initial position (mouse click position)
const x = event.clientX;
const y = event.clientY;
// Apply a slight random offset to each emoji
const offsetX = (Math.random() - 0.5) * 20;
const offsetY = (Math.random() - 0.5) * 20;
const emoji = new Emoji(emojiElement, x + offsetX, y + offsetY);
emojis.push(emoji);
}
});
// Animation loop
function animate(timestamp) {
if (!lastTime) lastTime = timestamp;
const deltaTime = (timestamp - lastTime) / 1000; // Convert to seconds
lastTime = timestamp;
// Update each emoji
emojis.forEach(emoji => emoji.update(deltaTime));
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// Optional: Remove emojis that are no longer visible (e.g., after some bounces)
// This can help performance if many emojis are created
setInterval(() => {
for (let i = emojis.length - 1; i >= 0; i--) {
const emoji = emojis[i];
// If the emoji is near the floor and its vertical velocity is very low, remove it
if (emoji.y >= (window.innerHeight - emoji.radius) && Math.abs(emoji.vy) < 50) {
document.body.removeChild(emoji.element);
emojis.splice(i, 1);
}
}
}, 1000);
</script>
</body>
</html>
How It Works
-
HTML Structure:
- A basic HTML structure with a
<style> block for styling and a <script> block for functionality.
-
Styling:
- The body is styled to occupy the full viewport with no margin and a light background.
- Emojis are absolutely positioned with
pointer-events: none to allow clicks to pass through them. They use transform: translate3d for smooth GPU-accelerated animations.
-
JavaScript Functionality:
- Emoji List: A predefined list of emojis to randomly select from.
- Emoji Class: Represents each emoji with properties like position (
x, y), velocity (vx, vy), and radius. It includes an update method to handle physics calculations.
- Click Event Listener: When the user clicks on the page, a random number of emojis (1-5) are created at the click position with slight random offsets and random initial horizontal velocities.
- Animation Loop: Uses
requestAnimationFrame to create a smooth animation loop. It calculates the deltaTime to update the position and velocity of each emoji based on gravity and handles collisions with the floor and walls. When an emoji collides with the floor or walls, its velocity is reversed and reduced by the bounceFactor to simulate energy loss.
- Cleanup Interval: Every second, the script checks if any emojis have settled near the floor with very low vertical velocity and removes them from the DOM and the emojis array to prevent memory leaks and performance issues.
Customization
- Gravity: Adjust the
GRAVITY constant to make emojis fall faster or slower.
- Bounce Factor: Change the
bounceFactor in the Emoji class to make emojis retain more or less energy after bouncing.
- Emoji Size: Modify the
font-size in the .emoji CSS class to make emojis larger or smaller.
- Emoji List: Add or remove emojis from the
emojiList array to customize which emojis appear.
Usage
- Save the above code into an
index.html file.
- Open the file in a web browser.
- Click anywhere on the page to generate emojis that fall and bounce with gravity and collision effects.
Enjoy your playful emoji animations!