Ukiyo.js

repository·main·Indexed 18 days ago

https://github.com/yitengjun/ukiyo-js

A lightweight, dependency-free JavaScript library for creating dynamic and efficient background parallax effects for images, videos, and CSS background images. Version 4.2.0 supports customization via JavaScript options or HTML data attributes, and provides an optional external requestAnimationFrame loop for synchronization with other animation libraries.

Tokens
2.9K
Snippets
16
Records
17
Agent score
61%

What's inside ukiyo-js

  1. Install Ukiyo.js

    main

    You can install ukiyojs via npm, yarn, or pnpm, or include it directly in your HTML using a CDN link.

    Package Managers

    # npm
    npm install ukiyojs
    
    # yarn
    yarn add ukiyojs
    
    # pnpm
    pnpm add ukiyojs

    CDN

    <script src="https://cdn.jsdelivr.net/npm/ukiyojs@4.1.2/dist/ukiyo.min.js"></script>
    npm install ukiyojs
  2. Use an external requestAnimationFrame loop

    main

    If you want to control the animation timing yourself (e.g., to sync with other animation libraries), set externalRAF: true in the instance options. You must then manually call the .animate() method within your own requestAnimationFrame loop.

    const parallax = new Ukiyo(".ukiyo", {
      externalRAF: true
    });
    
    function raf(time) {
      // animate parallax
      parallax.animate();
    
      requestAnimationFrame(raf);
    }
    
    requestAnimationFrame(raf);
  3. Initialize Ukiyo.js parallax effects

    main

    To use Ukiyo.js, first mark your target elements in HTML (e.g., using a class like ukiyo). Then, instantiate the Ukiyo class in JavaScript by passing a CSS selector, a NodeList, or an HTMLCollection.

    Supported HTML elements

    • <img>
    • <picture> (apply the class to the <img> inside)
    • <video>
    • Elements with background-image (apply the class to the <div>)

    JavaScript Initialization

    You can select elements using standard DOM methods.

    import Ukiyo from "ukiyojs";
    
    // Using a CSS selector
    new Ukiyo(".ukiyo");
    
    // Using a NodeList
    const images = document.querySelectorAll(".ukiyo");
    new Ukiyo(images);
    
    // Using an HTMLCollection
    const images = document.getElementsByClassName('ukiyo');
    new Ukiyo(images);
  4. Configure parallax via HTML data attributes

    main

    You can set individual options directly on HTML elements using data-u-* attributes. Note that the option name must be prefixed with u after the data- prefix.

    AttributeValuesDescription
    data-u-scalenumberSets the scale option.
    data-u-speednumberSets the speed option.
    data-u-willchangeEnables the willChange option (just add the attribute).
    data-u-wrapper-classstringSets the wrapperClass option.
    <img
      data-u-scale="2"
      data-u-speed="1.7"
      data-u-wrapper-class="wrapper-name"
      data-u-willchange
    >
  5. Configure Ukiyo.js Instance Options

    main

    When instantiating new Ukiyo(element, options), you can pass an options object to customize the parallax behavior.

    OptionTypeDefaultDescription
    scalenumber1.5Parallax image scaling factor (1~2 is recommended).
    speednumber1.5Parallax speed (1~2 is recommended).
    willChangebooleanfalseIf true, elements receive will-change: transform when parallax is active.
    wrapperClassstringnullCustom class name for the automatically generated wrapper element.
    externalRAFbooleanfalseSet to true to use an external requestAnimationFrame loop.
    const parallax = document.querySelector('.image');
    
    new Ukiyo(parallax, {
        scale: 1.5,
        speed: 1.5,
        willChange: true,
        wrapperClass: "ukiyo-wrapper",
        externalRAF: false
    });
  6. Troubleshooting: Safari and Lenis compatibility

    main

    When using Lenis for smooth scrolling, a bug in Safari may cause parallax effects to become distorted during scrolling.

    Workaround: You may need to apply pointer-events: none; to the parallax elements to prevent scroll events from affecting them.

    Warning: Applying pointer-events: none; will disable all interaction events (like clicks) on those elements.

  7. Ukiyo.js Instance Methods

    main

    The Ukiyo instance provides methods to manage its lifecycle and state.

    • reset(): Resets the instance and recalculates the size and position of the elements.
    • destroy(): Destroys the instance.
    const instance = new Ukiyo(".image");
    
    // Recalculate positions
    instance.reset();
    
    // Clean up the instance
    instance.destroy();
  8. Configure Ukiyo.js default options

    main

    When initializing Ukiyo.js, you can override the following default configuration options to control the parallax effect behavior and performance:

    • scale: A number representing the scaling factor applied to the image. Default is 1.5.
    • speed: A number representing the speed of the parallax effect. Default is 1.5.
    • wrapperClass: A string | null that specifies a custom CSS class for the element wrapper. Default is null.
    • willChange: A boolean that, if set to true, adds the will-change: transform CSS property to the element to hint at upcoming transformations for performance optimization. Default is false.
    • externalRAF: A boolean that, if set to true, tells the library to use an external requestAnimationFrame implementation instead of the browser's native one. Default is false.
    // Example of how these options might be applied in a configuration object
    const options = {
      scale: 2.0,
      speed: 1.0,
      wrapperClass: 'my-custom-wrapper',
      willChange: true,
      externalRAF: false
    };
  9. Reset or Destroy a Parallax instance

    main

    To manage memory and clean up the DOM, use the following methods:

    • reset(): Recalculates damping and resets the internal styles of the wrapper and the element, then re-applies the parallax transformation. Useful if the window is resized or layout changes.
    • destroy(): Completely removes the parallax effect. It disconnects any IntersectionObserver, removes all inline styles from the wrapper and the element, and removes the wrapper from the DOM, returning the original element to its original position in the document tree.
    // To clean up
    parallax.destroy();
  10. Initialize Ukiyo with the Ukiyo class

    main

    The Ukiyo class is the main entrypoint for the library. It manages multiple parallax instances for a set of elements. When instantiated, it automatically checks for browser support and initializes the parallax effect on the provided elements.

    Constructor Parameters:

    • elements: A TElement (can be a single element or a collection of elements) that must not be null.
    • options: An optional UkiyoOptions object to configure the behavior.

    If options.externalRAF is set to true, Ukiyo will not start its own internal animation loop, allowing you to control the animation timing manually via the animate() method.

    import Ukiyo from 'ukiyo-js';
    
    // Initialize Ukiyo with a single element or a collection
    const ukiyo = new Ukiyo(document.querySelectorAll('.parallax-element'), {
      // options here
    });
  11. Control animation with animate()

    main

    The animate() method triggers the animation cycle for all managed parallax instances.

    • If externalRAF was set to false (default) during initialization, calling animate() manually is unnecessary as the library manages its own requestAnimationFrame loop.
    • If externalRAF was set to true, you must call animate() manually (e.g., within your own requestAnimationFrame loop) to drive the parallax effect.
    // If initialized with externalRAF: true
    function loop() {
      ukiyo.animate();
      requestAnimationFrame(loop);
    }
    loop();
  12. Clean up resources with destroy()

    main

    The destroy() method performs full cleanup of the Ukiyo instance. It:

    1. Cancels the internal requestAnimationFrame loop.
    2. Removes window event listeners for resize and orientationchange.
    3. Calls destroy() on every individual parallax instance to free up resources.
    ukiyo.destroy();