Categories: CSSScriptWeb Design

Interactive WebGL Fluid Motion with Smokey Fluid Cursor

Smokey Fluid Cursor is a JavaScript library that creates interactive, real-time fluid motion following cursor movements.

The library uses WebGL to render the effect directly on an HTML canvas. This means the GPU handles the animation and runs smoothly without bogging down the main thread.

It supports both mouse and touch inputs, automatically scales to any screen resolution, and works across modern browsers without external dependencies.

Features:

  • Real-Time Physics Simulation: Implements Navier-Stokes fluid dynamics equations using WebGL shaders for accurate fluid behavior at 60fps.
  • Hardware Acceleration: Leverages GPU compute through WebGL for high-performance rendering that maintains smooth frame rates even on mid-range devices.
  • Adaptive Resolution Scaling: Automatically adjusts simulation and rendering resolution based on device pixel ratio and screen dimensions.
  • WebGL Compatibility Layer: Includes fallback mechanisms for devices without linear texture filtering support and gracefully handles both WebGL1 and WebGL2 contexts.
  • Dynamic Color System: Features HSV-based color generation with configurable transition speeds and brightness controls.
  • Configurable Physics Parameters: Exposes density dissipation, velocity damping, vorticity intensity, and pressure solver iterations for fine-tuning visual appearance.

See It In Action:


Use Cases:

  • Immersive Website Backgrounds: You can use it to create a dynamic, non-intrusive background that reacts to user interaction, adding a premium feel to a landing page or portfolio.
  • Enhanced Cursor Feedback: Instead of a standard cursor, the fluid effect provides immediate visual feedback for mouse movements, clicks, and drags.
  • Data Visualization Enhancement: Layer fluid dynamics behind or around real-time data dashboards to provide ambient visual context that responds to user interaction patterns.

How To Use It:

1. Add an HTML5 canvas element to your HTML document. The library will target this element by its ID. You should also add some basic styling to make the canvas fill the screen.

<canvas id=”smokey-fluid-canvas”></canvas>

2. Import the library into your document and initialize the fluid motion.

ES Module

<script type="module">
  import { initFluid } from "https://cdn.jsdelivr.net/npm/smokey-fluid-cursor@latest/dist/index.mjs";
  // Wait for the DOM to load before initializing
  window.addEventListener("DOMContentLoaded", () => {
    initFluid();
  });
</script>

IIFE

<script src="https://cdn.jsdelivr.net/npm/smokey-fluid-cursor@latest/dist/index.global.js"></script>
<script type="module">
  window.addEventListener("DOMContentLoaded", () => {
    if (window.SmokyFluid) {
      const fluid = SmokyFluid.initFluid();
    } else {
      console.error("SmokyFluid not found!");
    }
  });
</script>

3. If you’re using a bundler like Vite or Webpack, you can install it from a package manager.

# Yarn
$ yarn add smokey-fluid-cursor

# NPM
$ npm install smokey-fluid-cursor

# PNPM
$ pnpm install smokey-fluid-cursor

# BUN
$ bun add smokey-fluid-cursor
import { initFluid } from "smokey-fluid-cursor";

// Initialize with default settings
initFluid();

4. Customize the fluid motion with the following options:

Sponsored
Option Type Default Description
id string smokey-fluid-cursor The ID of the <canvas> element to use.
simResolution number 128 The resolution of the physics simulation. Lower for better performance.
dyeResolution number 512 The resolution of the rendered colors. Lower for better performance.
densityDissipation number 0.98 How fast the colors fade away. A value closer to 1 means slower fading.
velocityDissipation number 0.98 How fast the fluid’s movement slows down.
pressureIteration number 10 The number of iterations for the pressure solver. Higher is more accurate but costs performance.
curl number 30 The intensity of the swirls and vortices in the fluid.
splatRadius number 0.25 The radius of the “splat” effect when the cursor moves.
splatForce number 6000 The force applied by cursor movements.
shading boolean true Toggles a 3D lighting effect for more depth.
colorUpdateSpeed number 0.5 How quickly the fluid’s color palette cycles.
transparent boolean false If true, the canvas background will be transparent.
initFluid({
  id: "smokey-fluid-canvas",
  densityDissipation: 0.95,
  velocityDissipation: 0.97,
  curl: 40,
  splatRadius: 0.3,
  shading: false,
});

How It Works

The library implements a real-time fluid simulation using a technique called semi-Lagrangian advection combined with a projection method to solve the incompressible Navier-Stokes equations. This approach splits the simulation into discrete steps: advection moves quantities through the velocity field, diffusion spreads them out, and projection enforces the incompressibility constraint by removing divergence from the velocity field.

WebGL shaders handle all computation on the GPU. The velocity field is stored in a pair of textures that ping-pong between read and write targets, with each shader pass reading from one texture and writing to another. The curl shader calculates vorticity from neighboring velocity samples, which feeds into the vorticity confinement shader to amplify rotational motion. The divergence shader computes how much the velocity field is expanding or contracting at each point, then the pressure solver uses Jacobi iteration to find a pressure field that will counteract this divergence. The gradient subtraction shader applies this pressure gradient to make the velocity field divergence-free.

The advection shader uses backward particle tracing to determine what color or velocity should appear at each pixel by sampling from where a particle would have originated based on the current velocity field. When linear texture filtering isn’t available, the library implements manual bilinear interpolation in the shader to maintain smooth results. The splat shader creates Gaussian distributions of color and force at cursor positions, using the aspect ratio to maintain circular splats regardless of canvas dimensions.

Color generation uses HSV to RGB conversion with time-based hue cycling to create evolving palettes. The shading pass calculates surface normals from color gradients and applies diffuse lighting to simulate depth. The final composite uses alpha blending where the alpha channel derives from the brightest color component, creating the characteristic smokey appearance where brighter areas are more opaque.

FAQs

Q: The simulation runs slowly on mobile devices. How can I improve performance?
A: Reduce both simResolution and dyeResolution parameters. Mobile GPUs have less compute power, so dropping simResolution to 64 or 96 and dyeResolution to 256 or 384 typically restores smooth frame rates. You can also disable shading since the lighting calculations add overhead, and reduce pressureIteration to 8 or lower. Test on actual devices rather than desktop browser emulation because mobile GPU performance characteristics differ significantly.

Q: How do I place the fluid effect behind my website’s content?
A: The library automatically sets a low z-index on the canvas to place it in the background. If your content still appears behind it, you likely have a stacking context issue. Try setting position: relative and a higher z-index (e.g., z-index: 10) on your main content containers to ensure they render on top of the canvas.

Q: Can I set a static color or a specific color palette?
A: The library is designed for dynamic, cycling colors and doesn’t expose a direct API for setting a static palette. To achieve this, you would need to modify the internal functions that generate new colors within the library’s source code. It’s a good candidate for a fork if you need that level of control.

You Might Also Like:

The post Interactive WebGL Fluid Motion with Smokey Fluid Cursor appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

A Look Back, Feb. 27

50 Years Ago Coeducation appears to be settling in quietly at Amherst College these days,…

1 minute ago

South Hadley considers override to avoid severe cuts to schools and services

SOUTH HADLEY — Facing a $3.5 million fiscal cliff that threatens to shutter libraries and…

1 minute ago

Worthington voters back solar moratorium, approve K-9 funding at special TM

WORTHINGTON — Residents packed the RH Conwell Elementary School Tuesday night and overwhelmingly approved all…

2 minutes ago

Blaze rips through Hadley home, tenants escape unharmed

HADLEY — Four residents were displaced after a fire broke out at an East Street home…

2 minutes ago

Making News in Business, Feb. 27

Robbins elected as Northampton Chamber president NORTHAMPTON — The Greater Northampton Chamber of Commerce (GNCC)…

2 minutes ago

Hadley braces for sweeping cuts amid $1.5M budget deficit

HADLEY — One-day-a-week closures of Town Hall, the Hadley Public Library and the Council on…

2 minutes ago

This website uses cookies.