Game-Style Interactive 2D/3D Parallax Effects for Web – SuperParallax

Game-Style Interactive 2D/3D Parallax Effects for Web – SuperParallax
Game-Style Interactive 2D/3D Parallax Effects for Web – SuperParallax
SuperParallax is a JavaScript library that creates complex multi-layer parallax effects responding to both scroll and mouse movement.

The library offers two versions: a pure vanilla JavaScript implementation for 2D effects weighing approximately 6KB with zero dependencies, and a Three.js-powered variant that delivers true 3D depth through WebGL rendering.

Features:

  • Implements requestAnimationFrame for consistent 60fps animations across all layers.
  • Uses CSS translate3d transforms to leverage GPU acceleration for smooth rendering.
  • Automatically recalculates boundaries on window resize to maintain proper positioning.
  • Supports unlimited parallax layers with independent depth configurations.
  • Tracks mouse movement across the container for interactive depth effects.
  • Responds to scroll events with configurable intensity multipliers.
  • Offers axis-specific movement control for horizontal-only or vertical-only effects.
  • Rotates the camera based on mouse position for authentic 3D perspective.
  • Applies subtle 3D rotation to individual layers for enhanced depth perception.

How to use it:

1. Download the super-parallax.js library and include it in your HTML.

<script src="path/to/super-parallax.js"></script>

For WebGL-powered 3D effects, include Three.js from a CDN before loading SuperParallax3D:

<script src="/path/to/cdn/three.min.js"></script>
<script src="path/to/super-parallax-3d.js"></script>

2. The HTML structure consists of a container element and child elements marked with a data-parallax-layer attribute. The data-parallax-depth attribute controls how fast each layer moves: lower numbers mean slower movement (further away).

All HTML data attributes:

  • data-parallax-layer (required): Marks an element for parallax processing. Elements without this attribute remain static regardless of scroll or mouse position.
  • data-parallax-depth (number, default: 1): Sets the layer’s depth value, controlling movement speed relative to other layers. Values below 1 move slower (background layers), while values above 1 move faster (foreground layers). This serves as the default for both scroll and mouse if specific values are not set.
  • data-parallax-scroll (number, defaults to depth): Overrides the depth value specifically for scroll-based movement. This allows different speeds for scroll versus mouse tracking on the same layer.
  • data-parallax-mouse (number, defaults to depth): Overrides the depth value for mouse movement. Useful when you want aggressive mouse tracking but subtle scroll effects.
  • data-parallax-axis (string, default: ‘both’): Restricts movement to a single axis. Accepts ‘x’ for horizontal-only, ‘y’ for vertical-only, or ‘both’ for standard two-dimensional movement.
<div class="parallax-container">
  <!-- Background layer (moves slowly) -->
  <div data-parallax-layer data-parallax-depth="0.4">
    <img src="background.png" alt="Background" />
  </div>
  <!-- Middle layer -->
  <div data-parallax-layer data-parallax-depth="0.8">
    <img src="midground.png" alt="Midground" />
  </div>
  <!-- Foreground layer (moves quickly) -->
  <div data-parallax-layer data-parallax-depth="1.2">
    <img src="foreground.png" alt="Foreground" />
  </div>
</div>

3. Apply essential CSS to establish the container as the positioning context:

.parallax-container {
  position: relative;
  overflow: hidden;
  height: 100vh;
}

[data-parallax-layer] {
  position: absolute;
  width: 100%;
  height: 100%;
}

4. Create a new instance of SuperParallax and passing the container’s selector & an optional configuration object.

const parallax = new SuperParallax(".parallax-container", {
  // options here
});
// 3D Parallax
const parallax3d = new SuperParallax3D(".parallax-container", {
  // options here
});

5. Available options to customize the parallax effects.

  • scrollMultiplier (number, default: 1): Controls the intensity of scroll-based parallax movement. Higher values create more dramatic shifts between layers as the user scrolls. Setting this to 0 disables scroll effects entirely.
  • mouseMultiplier (number, default: 0.5): Adjusts how aggressively layers respond to mouse movement within the container. Lower values produce subtle tracking, while higher values create pronounced interactive effects. Set to 0 to disable mouse tracking.
  • smoothing (number, default: 0.1): Determines the easing factor for animations, accepting values between 0 and 1. Lower values produce smoother, more gradual transitions, while values closer to 1 create snappier responses. This applies to both scroll and mouse movements.
  • centerMouse (boolean, default: true): When enabled, normalizes mouse coordinates to a range of -1 to 1 with the container center as the origin. This creates symmetrical movement around the center point. Disable this for coordinate systems starting at the top-left corner.
  • resetOnMouseLeave (boolean, default: true): Returns all layers to their neutral position when the mouse exits the container. Disabling this maintains the current parallax state after the cursor leaves.
  • fov (number, default: 75): Sets the camera’s field of view in degrees. Lower values create a telephoto effect with less perspective distortion, while higher values provide a wide-angle view with more dramatic depth.
  • cameraZ (number, default: 5): Positions the camera along the Z-axis, controlling the distance from the scene. Higher values pull the camera back, showing more of the scene with less dramatic perspective.
const parallax = new SuperParallax(".parallax-container", {
  scrollMultiplier: 1, 
  mouseMultiplier: 0.5,
  smoothing: 0.1, 
  centerMouse: true,
  resetOnMouseLeave: true,
});
// 3D Parallax
const parallax3d = new SuperParallax3D(".parallax-container", {
  scrollMultiplier: 0.5,
  mouseMultiplier: 2,
  smoothing: 0.08,
  fov: 75,
  cameraZ: 5,
});

6. API methods.

  • start(): Begins the animation loop if it was previously stopped. The library starts automatically on initialization, so this is primarily useful after calling stop().
  • stop(): Pauses the animation loop, freezing all layers at their current positions. Event listeners remain attached.
  • destroy(): Completely tears down the parallax instance by stopping animations, removing event listeners, and resetting all transforms to their initial state. Use this before removing the container from the DOM.
  • addLayer(element, depth, scrollSpeed, mouseSpeed): Dynamically registers a new parallax layer after initialization. The depth parameter is required; scrollSpeed and mouseSpeed are optional and default to the depth value if omitted.
  • removeLayer(element): Unregisters a parallax layer, removing it from update calculations. The element remains in the DOM but stops responding to scroll or mouse movement.
  • setOptions(options): Updates configuration options without requiring re-initialization. Accepts any combination of the original options object properties.
  • updateBounds(): Manually recalculates the container’s bounding rectangle. The library calls this automatically on window resize, but you may need it after programmatic layout changes.

FAQs:

Q: Can SuperParallax work with dynamically loaded content?
A: Yes, use the addLayer() method to register new parallax layers after the initial page load. When loading content through AJAX or lazy-loading images, call addLayer() once the new DOM elements exist. If you need to batch-add multiple layers, consider calling stop() before adding them and start() afterward to avoid unnecessary calculations during the registration process.

Q: How do I debug parallax layers that are not moving?
A: Verify that your CSS positions the container as relative and sets overflow to hidden. Check that parallax layers use position: absolute within the container. Inspect the browser console for JavaScript errors during initialization. Confirm that data-parallax-layer attributes exist on the elements you expect to move, and verify depth values are defined as numbers rather than strings.

Q: What causes jittery or stuttering parallax movement?
A: Jittery motion typically stems from layout thrashing when JavaScript forces synchronous layout calculations. Verify that you are not reading layout properties like offsetHeight inside the animation loop. Check that images have defined dimensions to prevent layout shifts when they load. Reduce the smoothing value for more gradual transitions. If using the 3D version, confirm that Three.js is properly loaded before SuperParallax3D initialization.

Q: Should I use the 2D or 3D version for production projects?
A: The 2D version suits the vast majority of use cases and should be your default choice. It requires no external dependencies, works across all modern browsers without polyfills, and maintains a minimal bundle size. Reserve the 3D version for projects where WebGL effects are a core design requirement and you can guarantee modern browser support. The 3D version demands more processing power and may struggle on older mobile devices.

Q: How do I prevent parallax layers from moving outside the viewport?
A: Layers extending beyond viewport boundaries is expected behavior, as parallax creates the illusion of depth through differential movement. Make your layer images larger than the container to accommodate this movement. Calculate the extra space needed by multiplying your maximum depth value by the mouseMultiplier and scrollMultiplier. For a layer with depth 1.2, mouseMultiplier 0.5, and container width 1200px, the layer should extend at least (1200 * 1.2 * 0.5) = 720px beyond the visible area in each direction.

Q: Can I apply parallax to text content instead of images?
A: Yes, any DOM element marked with data-parallax-layer will move according to its depth value. Text content works particularly well as foreground layers with high depth values, creating separation from background images.

Related Resources:

The post Game-Style Interactive 2D/3D Parallax Effects for Web – SuperParallax appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading