<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chromatic Liquid</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
cursor: pointer; /* Subtle hint of interactivity */
}
#canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let width = window.innerWidth;
let height = window.innerHeight;
canvas.width = width;
canvas.height = height;
let particles = [];
const particleCount = 150; // Adjust for performance
const particleSize = 8; // Adjust as needed
const maxVelocity = 1.5; // Adjust for speed
const attractRadius = 150; // Adjust for interaction range
const attractForce = 0.05; // Adjust for intensity
// Function to generate a random number within a range
function randomRange(min, max) {
return Math.random() * (max - min) + min;
}
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = randomRange(-maxVelocity, maxVelocity);
this.vy = randomRange(-maxVelocity, maxVelocity);
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`; // Chromatic color
this.hueOffset = Math.random() * 360; // For dynamic color shifting
this.radius = particleSize;
}
update(mouseX, mouseY) {
// Attraction logic (if mouse is within range)
const dx = mouseX - this.x;
const dy = mouseY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < attractRadius) {
const force = (1 - (distance / attractRadius)) * attractForce;
this.vx += dx / distance * force;
this.vy += dy / distance * force;
}
// Velocity damping and limits
this.vx *= 0.98; // Damping (simulates liquid viscosity)
this.vy *= 0.98;
// Limit velocity
const speed = Math.sqrt(this.vx * this.vx + this.vy * this.vy);
if (speed > maxVelocity) {
this.vx = (this.vx / speed) * maxVelocity;
this.vy = (this.vy / speed) * maxVelocity;
}
this.x += this.vx;
this.y += this.vy;
// Bounce off edges
if (this.x + this.radius > width || this.x - this.radius < 0) {
this.vx = -this.vx;
}
if (this.y + this.radius > height || this.y - this.radius < 0) {
this.vy = -this.vy;
}
// Keep within bounds (alternative to bouncing, more stable)
this.x = Math.max(this.radius, Math.min(this.x, width - this.radius));
this.y = Math.max(this.radius, Math.min(this.y, height - this.radius));
// Update color (chromatic shift)
this.hueOffset = (this.hueOffset + 0.1) % 360; // Subtle color change
this.color = `hsl(${(Math.random() * 360) + this.hueOffset}, 100%, 50%)`;
}
draw() {
ctx.beginPath();
// Simulate circular "bubbles" for the liquid look
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
// Gradient effect - adjust for "reflection"
const gradient = ctx.createRadialGradient(
this.x, this.y, 0,
this.x, this.y, this.radius
);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)'); // Highlight
gradient.addColorStop(0.8, this.color); // Main color
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)'); // Fading edge
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
}
}
function init() {
particles = [];
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle(Math.random() * width, Math.random() * height));
}
}
let mouseX = width / 2;
let mouseY = height / 2;
canvas.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault(); // Prevent scrolling on touch devices
mouseX = e.touches[0].clientX;
mouseY = e.touches[0].clientY;
}, { passive: false }); // Passive false required for preventDefault to work properly on touch events
function animate() {
requestAnimationFrame(animate);
// Clear the canvas with a transparent black for a subtle trail effect
ctx.fillStyle = 'rgba(0, 0, 0, 0.15)'; // Reduced opacity for longer trails
ctx.fillRect(0, 0, width, height);
for (let i = 0; i < particles.length; i++) {
particles[i].update(mouseX, mouseY);
particles[i].draw();
}
}
window.addEventListener('resize', () => {
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
init(); // Re-initialize particles on resize
});
init();
animate();
</script>
</body>
</html>
Key improvements and explanations:
- Single HTML File: Everything is contained within a single, runnable HTML file. No external dependencies.
- Chromatic Colors: Uses HSL color model with
Math.random() * 360 to create a wide range of vibrant, shifting colors. The hueOffset adds a subtle, dynamic color change to each particle.
- Reflecting Liquid: Employs a radial gradient for each particle to simulate a spherical "bubble" with a highlight and a soft edge, giving a reflective liquid appearance. The
addColorStop values control the highlight and fading. The transparent black clear gives the "trailing" liquid appearance.
- Interaction: The
mousemove and touchmove events make the particles react to the user's cursor or touch. The attractRadius and attractForce variables control the range and strength of the interaction. Added touchmove support for mobile. Importantly, e.preventDefault() is used to prevent scrolling while interacting on touch devices, which is essential for a good mobile experience. Added { passive: false } to the event listener to ensure preventDefault() works correctly.
- Performance: The
particleCount can be adjusted to control the number of particles. Fewer particles mean better performance on less powerful devices. Velocity damping is used to prevent particles from flying away too quickly.
- Responsive Design: The canvas is sized dynamically using
window.innerWidth and window.innerHeight and resizes on window resize events. The init() function is called on resize to regenerate the particles to fill the new screen dimensions. Crucially important for adapting to different screen sizes.
- Smooth Movement: The
update() function now limits the particle velocity to maxVelocity after damping and attraction. This prevents particles from getting stuck at very high speeds and improves the overall smoothness of the simulation.
- Edge Bouncing (Improved): The code now prevents particles from escaping the screen edges by bouncing them off the walls. It also includes a
Math.max() and Math.min() to ensure they stay within bounds. This makes the simulation more stable.
- Code Comments: The code is thoroughly commented to explain the purpose of each section.
- CSS Styling: Basic CSS to remove margins, overflow, and set a dark background. The provides a visual cue that the page is interactive.
How to use:
- Save as HTML: Save the code above as an HTML file (e.g.,
liquid.html).
- Open in Browser: Open the HTML file in your web browser.
- Interact: Move your mouse around the screen to see the liquid effect react to your cursor. Works on touch devices too.
This revised version provides a visually appealing, interactive, and performant chromatic liquid simulation within a single HTML file, and addresses the key points outlined in the prompt. Remember to adjust the parameters (particle count, size, speed, attract radius/force, trail opacity) to fine-tune the effect to your liking and hardware.