pixi-viewport

repository·master·Indexed 23 days ago

https://github.com/pixijs-userland/pixi-viewport

A highly configurable 2D camera and viewport system for PIXI.js (version 6.0.3). It provides advanced interaction features including dragging, pinch-to-zoom, mouse wheel zooming, decelerated dragging, target following, and snapping. The library includes a plugin system with capabilities for smooth animations (Animate plugin), edge bouncing (Bounce plugin), movement restriction (Clamp plugin), and zoom level limits (ClampZoom plugin).

Tokens
10.1K
Snippets
11
Records
52
Agent score
77%

What's inside pixi-viewport

  1. Configure Viewport events (PIXI v7+)

    master

    In PIXI v7 and later, options.interaction has been removed. You must pass options.events to the Viewport constructor for it to function correctly. The events object can be retrieved from renderer.events or app.renderer.events.

    const viewport = new Viewport({ events: renderer.events });
    
    // or
    // const viewport = new Viewport({ events: app.renderer.events });
  2. Migrate from pixi-viewport v3 to v4

    master

    When migrating from v3 to v4, note two main changes:

    1. Importing: You must now import Viewport as a named export.
    2. Plugins: Plugin management has moved from direct methods on the viewport to the viewport.plugins object.
    // v3 style import (incorrect for v4)
    // const Viewport = require('pixi-viewport')
    
    // v4 style import
    import { Viewport } from "pixi-viewport";
    
    // or with require
    const Viewport = require("pixi-viewport").Viewport;
  3. Use pixi-viewport via CDN/Script tags

    master

    If you are not using a package manager, you can grab the latest release and include the scripts in your HTML. Note that when using the global script, the constructor is accessed via pixi_viewport.Viewport.

    <script src="/directory-to-file/pixi.js"></script>
    <script src="/directory-to-file/viewport.min.js"></script>
    <!-- or <script type="module" src="/directory-to-file/esm/viewport.es.js"></script> -->
    <script>
      const Viewport = new pixi_viewport.Viewport(options);
    </script>
  4. Basic usage of Viewport

    master

    To use the viewport, create a new Viewport instance, providing the screen dimensions, world dimensions, and the PIXI renderer's events. Add the viewport to your PIXI stage and activate desired plugins like drag(), pinch(), wheel(), or decelerate().

    import * as PIXI from "pixi.js";
    import { Viewport } from "pixi-viewport";
    
    const app = new PIXI.Application();
    document.body.appendChild(app.view);
    
    // create viewport
    const viewport = new Viewport({
      screenWidth: window.innerWidth,
      screenHeight: window.innerHeight,
      worldWidth: 1000,
      worldHeight: 1000,
      events: app.renderer.events, // the interaction module is important for wheel to work properly when renderer.view is placed or scaled
    });
    
    // add the viewport to the stage
    app.stage.addChild(viewport);
    
    // activate plugins
    viewport.drag().pinch().wheel().decelerate();
    
    // add a red box
    const sprite = viewport.addChild(new PIXI.Sprite(PIXI.Texture.WHITE));
    sprite.tint = 0xff0000;
    sprite.width = sprite.height = 100;
    sprite.position.set(100, 100);
  5. Configure Decelerate plugin options

    master

    When initializing the Decelerate plugin, you can provide an IDecelerateOptions object to fine-tune the momentum behavior:

    OptionTypeDefaultDescription
    frictionnumber0.95The percent of velocity retained after movement. Must be between 0 and 1 (exclusive). Higher values mean more momentum.
    bouncenumber0.8The percent of velocity retained when hitting viewport boundaries (only applicable if viewport.bounce() is active).
    minSpeednumber0.01The minimum velocity threshold. Once velocity falls below this value, the movement stops.
    const options: IDecelerateOptions = {
        friction: 0.98,
        bounce: 0.8,
        minSpeed: 0.01
    };
  6. Configure the Viewport with IViewportOptions

    master

    When instantiating a Viewport, you can provide an options object of type IViewportOptions to define the initial state of the camera and its interaction behavior.

    Key options include:

    • screenWidth / screenHeight: The dimensions of the visible area (defaults to window.innerWidth/innerHeight).
    • worldWidth / worldHeight: The dimensions of the coordinate system being viewed.
    • threshold: The number of pixels to move before triggering an input event like drag or pinch (default: 5).
    • passiveWheel: Whether the 'wheel' event is passive (default: true).
    • stopPropagation: Whether to stop propagation of events impacting the viewport (default: false).
    • noTicker: If true, you must manually call update() on each frame.
    • events: An instance of PIXI.EventSystem (required).
    • ticker: The PIXI.Ticker used for updates (default: PIXI.Ticker.shared).
    • disableOnContextMenu: If true, removes the default context menu behavior from the viewport's DOM element.
  7. Configure the Bounce plugin

    master

    The Bounce plugin adds a bouncing effect when the viewport hits its edges. You can customize which sides trigger a bounce, the duration of the bounce, the easing function, and how the viewport behaves when the world is smaller than the screen (underflow).

    IBounceOptions

    OptionTypeDefaultDescription
    sides'all' | 'horizontal' | 'vertical' | string'all'Which sides trigger a bounce. Can be 'all', 'horizontal', 'vertical', or a combination like 'top-bottom-right'.
    frictionnumber0.5Friction applied to decelerate if the decelerate plugin is active.
    timenumber150Duration of the bounce effect in milliseconds.
    bounceBoxRectangle | nullnullA custom Rectangle to use as the bounce boundary instead of the default viewport dimensions.
    easeany'easeInOutSine'An easing function or a name of a supported easing (e.g., from easings.net).
    underflow'center' | string'center'Determines where to place the world if it is too small for the screen. Options include 'center', or specific sides like 'top', 'bottom', 'left', 'right'.
  8. Configure the SnapZoom plugin

    master

    The SnapZoom plugin allows the viewport to snap its zoom level to specific increments based on a target width or height. This is useful for creating 'fit-to-size' animations or snapping to specific zoom levels.

    Options

    OptionTypeDefaultDescription
    widthnumber0The desired width to snap to. If provided, the plugin maintains aspect ratio based on this width.
    heightnumber0The desired height to snap to. If provided, the plugin maintains aspect ratio based on this height.
    timenumber1000Duration of the snapping animation in milliseconds.
    easeany'easeInOutSine'An easing function or a string name of an easing function (e.g., from easings.net).
    centerPoint | nullnullA pixi.js.Point to use as the center during the zoom animation. If null, it uses the current viewport center.
    interruptbooleantrueIf true, any user input on the viewport will pause the snapping animation.
    removeOnCompletebooleanfalseIf true, the plugin is automatically removed from the viewport after the animation finishes.
    removeOnInterruptbooleanfalseIf true, the plugin is automatically removed if user input interrupts the animation.
    forceStartbooleanfalseIf true, the snapping animation starts immediately upon plugin instantiation, even if the viewport is already at the target zoom.
    noMovebooleanfalseIf true, the viewport will only change its scale (zoom) and will not move its center during the animation.

    Events

    SnapZoom emits the following events on the Viewport instance:

    • snap-zoom-start: Emitted when the snapping animation begins.
    • snap-zoom-end: Emitted when the snapping animation reaches its target.
  9. Configure the Drag plugin

    master

    The Drag plugin enables panning of the viewport via mouse or touch. You can customize its behavior using IDragOptions when initializing the plugin.

    Key configuration options include:

    • direction: The axis to drag on ('all', 'x', or 'y'). Default is 'all'.
    • pressDrag: Whether clicking/pressing triggers a drag. Default is true.
    • mouseButtons: Which mouse buttons trigger dragging. Use 'all', 'left', 'right', 'middle', or combinations like 'middle-right'. Note: if using right-click, you may need to set viewport.options.disableOnContextMenu to true.
    • keyToPress: An array of keyboard code strings (e.g., ['ShiftLeft']) that must be held to enable dragging.
    • wheel: Whether to use the mouse wheel to scroll the viewport. Default is true.
    • wheelScroll: Number of pixels to scroll per wheel spin. Default is 1.
    • reverse: Reverses the wheel scroll direction. Default is false.
    • underflow: Determines where to place the world if it is smaller than the screen. Options are 'center', or specific directions like 'left', 'right', 'top', 'bottom'. Default is 'center'.
    • factor: A multiplier for drag speed. Default is 1.