Skip to content
The Chat Archive
gemini-2.5-flash-preview-04-17· Google LMArena Human Preference 140K

Generate me a visually appealing website with moving chromatic and reflecting liquid…

  1. User

    Generate me a visually appealing website with moving chromatic and reflecting liquid that interacts with clicks from the user. Make it into a single HTML file

  2. Assistant

    Okay, here is a single HTML file that uses a <canvas> element and JavaScript to simulate moving, chromatic, and reflecting liquid that reacts to user clicks.

    It uses a common "water ripple" simulation technique and renders it by calculating pixel colors based on the height and slope of the simulated surface, creating chromatic and reflective effects.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Interactive Liquid</title>
        <style>
            body {
                margin: 0;
                overflow: hidden;
                background-color: #000; /* Ensure black background */
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                font-family: sans-serif;
            }
            canvas {
                display: block;
                position: absolute; /* Position canvas behind overlay text */
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 1; /* Ensure canvas is behind the text */
            }
            .overlay {
                position: relative; /* Position text above canvas */
                z-index: 2;
                color: white;
                text-align: center;
                text-shadow: 0 0 5px rgba(0,0,0,0.5);
                padding: 20px;
            }
            h1 {
                margin-top: 0;
                font-size: 3em;
                text-shadow: 2px 2px 5px rgba(0,0,0,0.7);
            }
            p {
                 font-size: 1.2em;
                 max-width: 600px;
                 margin: 10px auto;
                 line-height: 1.5;
            }
            /* Optional: Add some subtle animation or style to the text */
            .overlay h1, .overlay p {
                 opacity: 0.9;
            }
        </style>
    </head>
    <body>
    
        <canvas id="liquidCanvas"></canvas>
    
        <div class="overlay">
            <h1>Interactive Liquid</h1>
            <p>Click anywhere on the screen to create ripples and interact with the chromatic, reflecting surface.</p>
        </div>
    
        <script>
            const canvas = document.getElementById('liquidCanvas');
            const ctx = canvas.getContext('2d');
    
            let width, height;
            let simWidth, simHeight; // Simulation grid size
            const DAMPING = 0.98; // How fast waves decay
            const SPREAD = 0.05; // How fast waves spread
            const PIXEL_SIZE = 1; // Number of canvas pixels per simulation point (1 for 1:1)
    
            let buffer1, buffer2; // Two buffers for the simulation
            let currentBuffer, previousBuffer; // Pointers to the current and previous buffers
    
            let imageData; // For drawing pixel data directly
    
            // Function to initialize or resize the simulation and canvas
            function init() {
                width = window.innerWidth;
                height = window.innerHeight;
                canvas.width = width;
                canvas.height = height;
    
                // Make simulation grid match canvas size if PIXEL_SIZE is 1, otherwise scale
                simWidth = Math.floor(width / PIXEL_SIZE);
                simHeight = Math.floor(height / PIXEL_SIZE);
    
                // Initialize simulation buffers (using Float32Array for performance)
                buffer1 = new Float32Array(simWidth * simHeight);
                buffer2 = new Float32Array(simWidth * simHeight);
    
                // Start with buffer1 as current, buffer2 as previous
                currentBuffer = buffer1;
                previousBuffer = buffer2;
    
                // Create ImageData object once
                imageData = ctx.createImageData(width, height);
    
                // Add some initial random drops
                for(let i = 0; i < 10; i++) {
                     addDrop(
                         Math.random() * width,
                         Math.random() * height,
                         Math.random() * 500 + 500 // Random strength
                     );
                }
            }
    
            // Function to add a drop (disturbance) to the water surface
            function addDrop(x, y, strength) {
                // Map canvas coordinates to simulation grid coordinates
                const simX = Math.floor(x / PIXEL_SIZE);
                const simY = Math.floor(y / PIXEL_SIZE);
    
                // Ensure coordinates are within bounds
                if (simX < 0 || simX >= simWidth || simY < 0 || simY >= simHeight) {
                    return;
                }
    
                // Apply the disturbance to a small area
                const radius = 3; // Radius of the drop effect
                for (let dy = -radius; dy <= radius; dy++) {
                    for (let dx = -radius; dx <= radius; dx++) {
                        const nx = simX + dx;
                        const ny = simY + dy;
    
                        // Check bounds again
                        if (nx >= 0 && nx < simWidth && ny >= 0 && ny < simHeight) {
                            const distSq = dx * dx + dy * dy;
                            if (distSq <= radius * radius) {
                                 // Add strength, weighted by distance from center
                                 currentBuffer[ny * simWidth + nx] += strength * (1 - Math.sqrt(distSq) / radius);
                            }
                        }
                    }
                }
            }
    
            // Main simulation loop (updates the buffer values)
            function updateSimulation() {
                // Swap buffers for the next iteration
                let temp = previousBuffer;
                previousBuffer = currentBuffer;
                currentBuffer = temp;
    
                // Iterate through the grid (excluding boundaries)
                for (let y = 1; y < simHeight - 1; y++) {
                    for (let x = 1; x < simWidth - 1; x++) {
                        const i = y * simWidth + x;
    
                        // Calculate the next value based on neighbors and previous value
                        // This is a simplified 2D wave equation step
                        currentBuffer[i] = (
                            previousBuffer[i - 1] + // left
                            previousBuffer[i + 1] + // right
                            previousBuffer[i - simWidth] + // up
                            previousBuffer[i + simWidth]  // down
                        ) / 2 - currentBuffer[i];
    
                        // Apply damping
                        currentBuffer[i] *= DAMPING;
    
                        // Optional: Apply spread (can make it look more fluid)
                        // Not strictly necessary for the core effect
                        // previousBuffer[i - 1] += currentBuffer[i] * SPREAD;
                        // previousBuffer[i + 1] += currentBuffer[i] * SPREAD;
                        // previousBuffer[i - simWidth] += currentBuffer[i] * SPREAD;
                        // previousBuffer[i + simWidth] += currentBuffer[i] * SPREAD;
                    }
                }
            }
    
            // Main rendering loop (draws the simulation to the canvas)
            function render() {
                const data = imageData.data;
    
                // Iterate through the canvas pixels
                for (let y = 0; y < height; y++) {
                    for (let x = 0; x < width; x++) {
                        // Map canvas pixel to simulation grid point
                        const simX = Math.floor(x / PIXEL_SIZE);
                        const simY = Math.floor(y / PIXEL_SIZE);
    
                        const i = simY * simWidth + simX;
                        const pixelIndex = (y * width + x) * 4; // RGBA
    
                        // --- Calculate Visuals ---
    
                        // Get height and difference from neighbors (proxy for slope/normal)
                        let heightValue = currentBuffer[i];
                        let dx = (simX > 0 ? currentBuffer[i] - currentBuffer[i - 1] : 0) * 255; // Horizontal difference
                        let dy = (simY > 0 ? currentBuffer[i] - currentBuffer[i - simWidth] : 0) * 255; // Vertical difference
    
                        // Calculate lightness/brightness based on height and slope
                        // Higher points are brighter (reflection/highlight)
                        // Slope also affects brightness (simulated normal pointing towards light)
                        let lightness = 128 + heightValue * 1000 + (dx * dx + dy * dy) * 0.005; // Adjust multipliers
    
                        // Calculate color (chromatic effect) based on slope direction/magnitude or height
                        // Simple approach: map vertical difference (dy) to hue
                        let hue = (Math.atan2(dy, dx) / Math.PI) * 180 + 180; // Map angle to hue [0, 360]
                         // Alternative hue mapping: based on height value or just a fixed chromatic shift
                         // let hue = (heightValue * 500) % 360; // Shift hue based on height
                         // let hue = (x + y) % 360; // Static chromatic background distortion
    
    
                        // Ensure lightness is within 0-255 range
                        lightness = Math.max(0, Math.min(255, lightness));
    
                        // Convert HSL (Hue, Saturation, Lightness) to RGB
                        // Using a simple HSL to RGB conversion
                        let saturation = 1; // Use full saturation for vibrant colors
    
                        // HSL to RGB conversion helper function (simplified for 0-1 range)
                        function hslToRgb(h, s, l) {
                             let r, g, b;
                             h /= 360; s /= 1; l /= 1;
    
                             if (s === 0) {
                                 r = g = b = l; // achromatic
                             } else {
                                 const hue2rgb = (p, q, t) => {
                                     if (t < 0) t += 1;
                                     if (t > 1) t -= 1;
                                     if (t < 1 / 6) return p + (q - p) * 6 * t;
                                     if (t < 1 / 2) return q;
                                     if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                                     return p;
                                 };
                                 const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                                 const p = 2 * l - q;
                                 r = hue2rgb(p, q, h + 1 / 3);
                                 g = hue2rgb(p, q, h);
                                 b = hue2rgb(p, q, h - 1 / 3);
                             }
    
                             return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
                         }
    
                         // Convert calculated HSL (using lightness from simulation, hue from slope)
                         const [r, g, b] = hslToRgb(hue, saturation, lightness / 255);
    
    
                        // Set pixel data (RGBA)
                        data[pixelIndex] = r;     // Red
                        data[pixelIndex + 1] = g; // Green
                        data[pixelIndex + 2] = b; // Blue
                        data[pixelIndex + 3] = 255; // Alpha (fully opaque)
                    }
                }
    
                // Put the calculated pixel data onto the canvas
                ctx.putImageData(imageData, 0, 0);
            }
    
            // Animation loop
            function animate() {
                updateSimulation();
                render();
                requestAnimationFrame(animate); // Call animate again for the next frame
            }
    
            // Event Listeners
            window.addEventListener('resize', init); // Re-initialize on window resize
            canvas.addEventListener('mousedown', (e) => {
                addDrop(e.clientX, e.clientY, 1000); // Add a drop on click
            });
             canvas.addEventListener('touchstart', (e) => {
                // Prevent default touch behavior (like scrolling)
                e.preventDefault();
                // Use the first touch point
                const touch = e.touches[0];
                addDrop(touch.clientX, touch.clientY, 1000);
            });
    
            // Start the simulation and animation
            init(); // Initial setup
            animate(); // Start the animation loop
    
        </script>
    
    </body>
    </html>
    

    Explanation:

    1. Single File Structure: All HTML, CSS, and JavaScript are contained within the single index.html file.
      • <style> block in <head> contains the CSS to make the canvas fill the screen and position the overlay text.
      • <script> block at the end of <body> contains all the JavaScript logic.
    2. Canvas: A <canvas> element is used as the drawing surface.
    3. CSS: Styles the body to remove default margin and hide overflow, making the canvas full screen. The canvas is positioned absolutely behind a text div.overlay.
    4. Simulation:
      • The core effect is created using a "water ripple" simulation algorithm. This involves a 2D grid represented by a 1D Float32Array for performance.
      • Double Buffering: Two arrays (buffer1, buffer2) are used. In each animation frame, the state of the water is read from one buffer (previousBuffer) and the next state is calculated and written into the other buffer (currentBuffer). Then, the pointers are swapped (currentBuffer becomes the new previousBuffer and vice versa). This prevents the simulation from using values that have already been updated within the same frame, which can cause instability.
      • Wave Equation: The core update step currentBuffer[i] = (neighbors_sum / 2) - currentBuffer[i]; is a simplified numerical solution to a 2D wave equation. It calculates the "acceleration" of the water level based on the difference between the average height of its neighbors and its current height.
      • Damping: currentBuffer[i] *= DAMPING; reduces the energy of the waves over time, making them fade out.
    5. Interaction:
      • Event listeners for mousedown (for mouse clicks) and touchstart (for touch) are added to the canvas.
      • When a click/touch occurs, the addDrop function is called.
      • addDrop takes the screen coordinates, maps them to the simulation grid coordinates, and adds a positive value (strength) to the currentBuffer at that location and its immediate neighbors. This creates the initial disturbance.
    6. Rendering:
      • Instead of drawing shapes (fillRect), the code uses ctx.createImageData and ctx.putImageData for performance. This allows direct manipulation of pixel color data.
      • The render function iterates through each pixel on the canvas.
      • For each pixel, it maps back to the corresponding point in the simulation grid (using PIXEL_SIZE).
      • It calculates the heightValue from the simulation buffer and the dx, dy values, which represent the difference in height from the left and top neighbors, acting as proxies for the surface slope or "normal" direction.
      • Reflecting Effect: lightness is calculated based on the heightValue (higher points are brighter, simulating highlights) and the magnitude of dx and dy (steeper slopes are also made brighter, simulating light reflecting off angled surfaces).
      • Chromatic Effect: hue is calculated based on the angle derived from dx and dy using Math.atan2. This maps the direction of the slope to a specific color hue. As waves move and slopes change direction, the color at that point changes, creating the chromatic effect.
      • HSL to RGB: The calculated hue (0-360), saturation (fixed at 1 for vibrancy), and lightness (0-255, calculated from simulation data) are converted to RGB values. A simple hslToRgb helper function is included for this.
      • The calculated RGBA values are written directly into the imageData.data array for each pixel.
      • Finally, ctx.putImageData(imageData, 0, 0) draws the entire imageData to the canvas in one go.
    7. Animation Loop: requestAnimationFrame(animate) is used to create a smooth animation loop, calling updateSimulation and render repeatedly.
    8. Resize Handling: The init function is called on window resize to adjust the canvas and simulation grid size, preventing visual distortion and ensuring the simulation covers the new window dimensions.

    To use this, save the code as an .html file (e.g., liquid.html) and open it in a web browser. Click or touch the screen to see the effect.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.