### Install Dependencies for PixiJS Development Source: https://pixijs.download/release/docs/media/CONTRIBUTING This command installs the necessary Node.js dependencies required to build PixiJS. Ensure you have Node.js and npm installed and have forked the PixiJS repository. ```bash npm install ``` -------------------------------- ### Basic pixi.js Application Setup and Usage Source: https://pixijs.download/release/docs/index This JavaScript code demonstrates how to initialize a PixiJS application, load an asset (a bunny sprite), add it to the stage, center it, and make it rotate continuously using the application's ticker. It requires the pixi.js library to be installed. ```javascript import { Application, Assets, Sprite } from 'pixi.js'; (async () => { // Create a new application const app = new Application(); // Initialize the application await app.init({ background: '#1099bb', resizeTo: window }); // Append the application canvas to the document body document.body.appendChild(app.canvas); // Load the bunny texture const texture = await Assets.load('https://pixijs.com/assets/bunny.png'); // Create a bunny Sprite const bunny = new Sprite(texture); // Center the sprite's anchor point bunny.anchor.set(0.5); // Move the sprite to the center of the screen bunny.x = app.screen.width / 2; bunny.y = app.screen.height / 2; app.stage.addChild(bunny); // Listen for animate update app.ticker.add((time) => { // Just for fun, let's rotate mr rabbit a little. // * Delta is 1 if running at 100% performance * // * Creates frame-independent transformation * bunny.rotation += 0.1 * time.deltaTime; }); })(); ``` -------------------------------- ### Start PixiJS Incremental Compilation Source: https://pixijs.download/release/docs/media/CONTRIBUTING Starts a process that watches the PixiJS source files and recompiles them incrementally. This is useful for a faster development workflow, allowing you to see changes reflected quickly without a full rebuild. Run this in one terminal, and 'npm run test' in another. ```bash npm start ``` -------------------------------- ### Install pixi.js using npm Source: https://pixijs.download/release/docs/index This command installs the pixi.js library, which is a dependency for using the PixiJS graphics engine in your web projects. It can be used with the PixiJS Create CLI or added to an existing project. ```bash npm install pixi.js ``` -------------------------------- ### PixiJS: Handle 'touchstart' event with property-based handler Source: https://pixijs.download/release/docs/gif This code snippet demonstrates the 'ontouchstart' property-based event handler in PixiJS. It fires when a touch interaction begins on the screen. The example scales the sprite down to 0.9. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using property-based handler sprite.ontouchstart = (event) => { sprite.scale.set(0.9); }; ``` -------------------------------- ### Run PixiJS Visual Regression Tests Source: https://pixijs.download/release/docs/media/CONTRIBUTING Executes the visual regression tests for PixiJS. These tests compare rendered scenes against reference images. Ensure your scene files are correctly formatted and located in the tests/visual/scenes directory. This command assumes dependencies are installed. ```bash npm run test:scene ``` -------------------------------- ### Run PixiJS Automated Tests Source: https://pixijs.download/release/docs/media/CONTRIBUTING Executes the automated test suite for PixiJS. It is recommended to add a new test case for any bug fix to prevent regressions. This command assumes you have already installed dependencies and set up your development environment. ```bash npm test ``` -------------------------------- ### Mouse enter/leave events in PIXI.js Source: https://pixijs.download/release/docs/gif Examples for handling mouse enter and leave events in PIXI.js. Includes scaling transformations when pointer enters/leaves object bounds. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mouseenter', (event) => { sprite.scale.set(1.1); }); // Using property-based handler sprite.onmouseenter = (event) => { sprite.scale.set(1.1); }; ``` ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mouseleave', (event) => { sprite.scale.set(1.0); }); // Using property-based handler sprite.onmouseleave = (event) => { sprite.scale.set(1.0); }; ``` -------------------------------- ### NineSliceSprite Properties Source: https://pixijs.download/release/docs/scene This section details the various properties available for configuring a NineSliceSprite in PixiJS, including their types, descriptions, default values, and code examples. ```APIDOC ## NineSliceSprite Properties ### `Optional` renderable Controls whether this object can be rendered. If false the object will not be drawn, but the transform will still be updated. This is different from visible, which skips transform updates. **Type:** `boolean` **Default:** `true` #### Example ```javascript new Container({ renderable: false }); // Will not be drawn, but transforms will update ``` ### `Optional` rightWidth Width of the right vertical bar (B). Controls the size of the right edge that remains unscaled. **Type:** `number` **Default:** `10` #### Example ```javascript const sprite = new NineSliceSprite({ ..., rightWidth: 20 }); sprite.rightWidth = 20; // Set right border width ``` ### `Optional` rotation The rotation of the object in radians. **Type:** `number` **Note:** 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. #### Example ```javascript new Container({ rotation: Math.PI / 4 }); // Rotate 45 degrees new Container({ rotation: Math.PI / 2 }); // Rotate 90 degrees ``` ### `Optional` roundPixels Whether to round the x/y position to whole pixels. **Type:** `boolean` **Default:** `false` #### Example ```javascript const sprite = new NineSliceSprite({ ..., roundPixels: true }); ``` ### `Optional` scale The scale factors of this object along the local coordinate axes. **Type:** `number | PointData` **Default:** `(1, 1)` #### Example ```javascript new Container({ scale: new Point(2, 2) }); // Scale by 2x new Container({ scale: 0.5 }); // Scale by 0.5x new Container({ scale: { x: 1.5, y: 1.5 } }); // Scale by 1.5x ``` ### `Optional` setMask **Type:** `(options: Partial) => void` ### `Optional` skew The skew factor for the object in radians. Skewing is a transformation that distorts the object by rotating it differently at each point, creating a non-uniform shape. **Type:** `PointData` **Default:** `{ x: 0, y: 0 }` #### Example ```javascript new Container({ skew: new Point(0.1, 0.2) }); // Skew by 0.1 radians on x and 0.2 radians on y new Container({ skew: { x: 0.1, y: 0.2 } }); // Skew by 0.1 radians on x and 0.2 radians on y ``` ### `Optional` sortableChildren If set to true, the container will sort its children by `zIndex` value when the next render is called, or manually if `sortChildren()` is called. **Type:** `boolean` **Default:** `false` **Note:** This may not work nicely with the `addChildAt()` function, as the `zIndex` sorting may cause the child to automatically sorted to another position. #### Example ```javascript container.sortableChildren = true; ``` ### `Optional` tabIndex Sets the tabIndex of the shadow div. You can use this to set the order of the elements when using the tab key to navigate. **Type:** `number` **Default:** `0` #### Example ```javascript const container = new Container(); container.accessible = true; container.tabIndex = 0; const sprite = new Sprite(texture); sprite.accessible = true; sprite.tabIndex = 1; ``` ### texture The texture to use on the NineSliceSprite. **Type:** `Texture` **Default:** `Texture.EMPTY` #### Example ```javascript // Create a sprite with a texture const sprite = new NineSliceSprite({ texture: Texture.from('path/to/image.png') }); // Update the texture later sprite.texture = Texture.from('path/to/another-image.png'); ``` ### `Optional` tint The tint applied to the sprite. **Type:** `ColorSource` **Default:** `0xFFFFFF` #### Example ```javascript new Container({ tint: 0xff0000 }); // Red tint new Container({ tint: 'blue' }); // Blue tint new Container({ tint: '#00ff00' }); // Green tint new Container({ tint: 'rgb(0,0,255)' }); // Blue tint ``` ### `Optional` topHeight Height of the top horizontal bar (C). Controls the size of the top edge that remains unscaled. **Type:** `number` **Default:** `10` #### Example ```javascript const sprite = new NineSliceSprite({ ..., topHeight: 20 }); sprite.topHeight = 20; // Set top border height ``` ### `Optional` visible The visibility of the object. If false the object will not be drawn, and the transform will not be updated. **Type:** `boolean` **Default:** `true` #### Example ```javascript new Container({ visible: false }); // Will not be drawn and transforms will not update new Container({ visible: true }); // Will be drawn and transforms will update ``` ### `Optional` width Width of the NineSliceSprite. Modifies the vertices directly rather than UV coordinates. **Type:** `number` ``` -------------------------------- ### Mouse out/over events in PIXI.js Source: https://pixijs.download/release/docs/gif Examples for handling mouse out and over events in PIXI.js. Similar to enter/leave but with different bubbling behavior. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mouseout', (event) => { sprite.scale.set(1.0); }); // Using property-based handler sprite.onmouseout = (event) => { sprite.scale.set(1.0); }; ``` -------------------------------- ### GET /clone Source: https://pixijs.download/release/docs/gif Creates an independent copy of this GifSprite instance with its own playback state. ```APIDOC ## GET /clone ### Description Creates an independent copy of this GifSprite instance. Useful for creating multiple animations that share the same source data but can be controlled independently. ### Method GET ### Endpoint /clone ### Response #### Success Response (200) - **clonedSprite** (GifSprite) - A new GifSprite instance with the same properties #### Response Example ``` { "clonedSprite": { "animationSpeed": 0.5, "playing": false } } ``` ``` -------------------------------- ### Handle mousedown event in PIXI.js Source: https://pixijs.download/release/docs/scene Demonstrates how to set up event handlers for the mousedown event in PIXI.js. The example shows both emitter-based and property-based handlers. ```TypeScript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mousedown', (event) => { sprite.alpha = 0.5; // Visual feedback console.log('Mouse button:', event.button); }); // Using property-based handler sprite.onmousedown = (event) => { sprite.alpha = 0.5; // Visual feedback console.log('Mouse button:', event.button); }; ``` -------------------------------- ### Toggle sprite visibility in PixiJS Source: https://pixijs.download/release/docs/gif Simple example showing how to hide and show a sprite by toggling its visible property. ```JavaScript // Basic visibility toggle sprite.visible = false; // Hide sprite sprite.visible = true; // Show sprite ``` -------------------------------- ### Handle Right Click Event in PixiJS Source: https://pixijs.download/release/docs/scene This example shows how to capture the `rightclick` event in PixiJS. It demonstrates setting up both an emitter handler and a property-based handler to log the coordinates where the right-click occurred. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('rightclick', (event) => { console.log('Right-clicked at:', event.global.x, event.global.y); }); // Using property-based handler sprite.onrightclick = (event) => { console.log('Right-clicked at:', event.global.x, event.global.y); }; ``` -------------------------------- ### Getting and Setting Alpha (Transparency) in PixiJS Source: https://pixijs.download/release/docs/gif Demonstrates how to get and set the `alpha` property of a PixiJS display object, which controls its transparency. The value ranges from 0 (fully transparent) to 1 (fully opaque). ```javascript // Basic transparency sprite.alpha = 0.5; // 50% opacity // Inherited opacity container.alpha = 0.5; const child = new Sprite(texture); child.alpha = 0.5; container.addChild(child); // child's effective opacity is 0.25 (0.5 * 0.5) ``` -------------------------------- ### Create and Control a GifSprite in Pixi.js Source: https://pixijs.download/release/docs/gif This example demonstrates how to load a GIF, create a GifSprite instance with various playback options, add it to the Pixi application stage, and control its playback using methods like play(), stop(), and setting the currentFrame. It utilizes Pixi.js's Assets module for loading and GifSprite for animation. ```javascript import { GifSprite, Assets } from 'pixi.js'; // Load and create a GIF sprite const source = await Assets.load('animation.gif'); const animation = new GifSprite({ source, animationSpeed: 1, loop: true, autoPlay: true }); // Add to stage app.stage.addChild(animation); // Control playback animation.play(); animation.stop(); animation.currentFrame = 5; // Jump to frame ``` -------------------------------- ### PixiJS Container Event Mode Example Source: https://pixijs.download/release/docs/gif Illustrates how to configure the event mode of a PixiJS Container to manage interaction events (touch, pointer, mouse). Different modes control event emission and hit testing behavior for the container and its children. ```javascript const sprite = new Sprite(texture); // Enable standard interaction (like buttons) sprite.eventMode = 'static'; sprite.on('pointerdown', () => console.log('clicked!')); // Enable for moving objects sprite.eventMode = 'dynamic'; sprite.on('pointermove', () => updatePosition()); // Disable all interaction sprite.eventMode = 'none'; // Only allow child interactions sprite.eventMode = 'passive'; ``` -------------------------------- ### Implement Per-Frame Updates with onRender in PixiJS Source: https://pixijs.download/release/docs/scene This code illustrates how to use the `onRender` callback in PixiJS for per-frame updates and animations. The example shows basic rotation animation for a container and how to remove the callback by setting it to null. ```javascript // Basic rotation animation const container = new Container(); container.onRender = () => { container.rotation += 0.01; }; // Cleanup when done container.onRender = null; // Removes callback ``` -------------------------------- ### Handle Tap Event on PixiJS Sprite Source: https://pixijs.download/release/docs/scene This example shows how to handle a `tap` event on a PixiJS sprite. It provides code for both emitter and property-based handlers, which log the tap coordinates when the sprite is tapped. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('tap', (event) => { console.log('Sprite tapped at:', event.global.x, event.global.y); }); // Using property-based handler sprite.ontap = (event) => { console.log('Sprite tapped at:', event.global.x, event.global.y); }; ``` -------------------------------- ### Mouse move tracking in PIXI.js Source: https://pixijs.download/release/docs/gif Demonstrates tracking mouse movements within a PIXI.js sprite. Shows how to get local coordinates relative to the sprite. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mousemove', (event) => { // Get coordinates relative to the sprite console.log('Local:', event.getLocalPosition(sprite)); }); // Using property-based handler sprite.onmousemove = (event) => { // Get coordinates relative to the sprite console.log('Local:', event.getLocalPosition(sprite)); }; ``` -------------------------------- ### Create NineSliceSprite with Options (JavaScript) Source: https://pixijs.download/release/docs/scene This example demonstrates how to create a basic nine-slice sprite using the NineSliceSpriteOptions. It specifies the texture, border dimensions (leftWidth, rightWidth, topHeight, bottomHeight), initial dimensions (width, height), and anchor point. This is useful for creating UI elements like buttons that need to scale uniformly. ```javascript const button = new NineSliceSprite({ texture: Texture.from('button.png'), leftWidth: 20, // Left border (A) rightWidth: 20, // Right border (B) topHeight: 20, // Top border (C) bottomHeight: 20, // Bottom border (D) width: 100, // Initial width height: 50, // Initial height anchor: 0.5, // Center anchor point }); ``` -------------------------------- ### Set Bounds Area for PixiJS Container Optimization Source: https://pixijs.download/release/docs/gif Provides an example of setting a `boundsArea` for a PixiJS container. This optimization prevents the renderer from recursively measuring child bounds, improving performance for complex scenes. ```javascript const container = new Container(); container.boundsArea = new Rectangle(0, 0, 500, 500); ``` -------------------------------- ### Handle PixiJS Sprite wheel Event Source: https://pixijs.download/release/docs/scene Provides examples for handling the 'wheel' event on a PixiJS Sprite, which triggers when the mouse wheel is scrolled over the object. Event handling can be done via sprite.on() or sprite.onwheel. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('wheel', (event) => { sprite.scale.x += event.deltaY * 0.01; // Zoom in/out sprite.scale.y += event.deltaY * 0.01; // Zoom in/out }); // Using property-based handler sprite.onwheel = (event) => { sprite.scale.x += event.deltaY * 0.01; // Zoom in/out sprite.scale.y += event.deltaY * 0.01; // Zoom in/out }; ``` -------------------------------- ### Mouse down event handling in PIXI.js Source: https://pixijs.download/release/docs/gif Example of handling mouse down events in PIXI.js. Requires 'eventMode' to be set to 'static'. Provides visual feedback when mouse button is pressed. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('mousedown', (event) => { sprite.alpha = 0.5; // Visual feedback console.log('Mouse button:', event.button); }); // Using property-based handler sprite.onmousedown = (event) => { sprite.alpha = 0.5; // Visual feedback console.log('Mouse button:', event.button); }; ``` -------------------------------- ### Create NineSliceSprite with width Source: https://pixijs.download/release/docs/scene Creates a NineSliceSprite with a specified width property. The width property controls the horizontal size of the sprite. This example shows both constructor initialization and direct property assignment. ```javascript const sprite = new NineSliceSprite({ ..., width: 200 }); sprite.width = 200; // Set the width of the sprite ``` -------------------------------- ### Setting zIndex for Rendering Order in PixiJS Source: https://pixijs.download/release/docs/gif Provides an example of how to set the `zIndex` property for PixiJS display objects to control their rendering order within a parent container. Higher `zIndex` values are rendered on top. ```javascript container.addChild(character, background, foreground); // Adjust rendering order background.zIndex = 0; character.zIndex = 1; foreground.zIndex = 2; ``` -------------------------------- ### Set NineSliceSprite Anchor (JavaScript) Source: https://pixijs.download/release/docs/scene Provides examples for setting the anchor point of a PixiJS NineSliceSprite. The anchor controls the origin for rotation, scaling, and positioning, and can be a uniform number or separate x/y values using PointData. ```javascript // Centered anchor const sprite = new NineSliceSprite({ ..., anchor: 0.5 }); sprite.anchor = 0.5; // Separate x/y anchor sprite.anchor = { x: 0.5, y: 0.5 }; // Right-aligned anchor sprite.anchor = { x: 1, y: 0 }; // Update anchor directly sprite.anchor.set(0.5, 0.5); ``` -------------------------------- ### Configure Autoplay for PixiJS Animations Source: https://pixijs.download/release/docs/gif Illustrates how to control whether a PixiJS `GifSprite` starts playing automatically upon creation using the `autoPlay` property. If set to `false`, playback must be initiated manually with `GifSprite.play()`. ```javascript const animation = new GifSprite({ source, autoPlay: true }); ``` -------------------------------- ### PixiJS Container Cursor Styles Example Source: https://pixijs.download/release/docs/gif Illustrates the use of various cursor styles with PixiJS sprites. This includes common CSS cursor types, direction cursors, and custom cursor URLs. Setting the `cursor` property changes the mouse pointer appearance when hovering over the object. ```javascript // Common cursor types sprite.cursor = 'pointer'; // Hand cursor for clickable elements sprite.cursor = 'grab'; // Grab cursor for draggable elements sprite.cursor = 'crosshair'; // Precise cursor for selection sprite.cursor = 'not-allowed'; // Indicate disabled state // Direction cursors sprite.cursor = 'n-resize'; // North resize sprite.cursor = 'ew-resize'; // East-west resize sprite.cursor = 'nesw-resize'; // Northeast-southwest resize // Custom cursor with fallback sprite.cursor = 'url("custom.png"), auto'; sprite.cursor = 'url("cursor.cur") 2 2, pointer'; ``` -------------------------------- ### PixiJS: Handle 'tap' event with property-based handler Source: https://pixijs.download/release/docs/gif This example illustrates the 'ontap' property-based event handler for PixiJS. It fires when a tap (touch) action is completed on a display object. The code logs the tap coordinates to the console. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using property-based handler sprite.ontap = (event) => { console.log('Sprite tapped at:', event.global.x, event.global.y); }; ``` -------------------------------- ### Track Animation Progress with GifSprite Source: https://pixijs.download/release/docs/gif Get the current animation progress as a value between 0 and 1. This is useful for tracking animation completion and implementing dynamic progress bars. The value is 0 at the start and 1 when complete, updating continuously based on current time and total duration. ```javascript const animation = new GifSprite({ source }); console.log('Progress:', Math.round(animation.progress * 100) + '%'); app.ticker.add(() => { progressBar.width = animation.progress * 200; // 200px total width }); if (animation.progress > 0.9) { console.log('Animation almost complete!'); } ``` -------------------------------- ### Pixi.js TickerCallback Usage Example Source: https://pixijs.download/release/docs/ticker Demonstrates how to use the TickerCallback type alias to add a function to the Pixi.js ticker. This callback allows access to timing properties like deltaTime and deltaMS for animation and game logic. ```typescript ticker.add((ticker) => { // Access deltaTime (dimensionless scalar ~1.0 at 60fps) sprite.rotation += 0.1 * ticker.deltaTime; // Access deltaMS (milliseconds elapsed) const progress = ticker.deltaMS / animationDuration; }); ``` -------------------------------- ### Initialize PixiJS Application Source: https://pixijs.download/release/docs/app Creates and initializes a PixiJS Application instance with specified dimensions and background color. Requires awaiting the asynchronous init() method before DOM manipulation. Appends the rendered canvas to document body for display. ```javascript import { Application } from 'pixi.js'; const app = new Application(); await app.init({ width: 800, height: 600, backgroundColor: 0x1099bb, }); document.body.appendChild(app.canvas); ``` -------------------------------- ### PixiJS Sprite Destroy Example Source: https://pixijs.download/release/docs/gif Shows how to destroy a PixiJS Sprite object, releasing resources and disabling functionality. This is essential for cleanup operations and preventing memory leaks. Setting `destroyed` to true disables all functionality and removes references. ```javascript // Cleanup with destroy sprite.destroy(); console.log(sprite.destroyed); // true ``` -------------------------------- ### GET /y Source: https://pixijs.download/release/docs/gif Gets the position of the container on the y axis relative to the local coordinates of the parent. This is an alias to position.y. ```APIDOC ## GET /y ### Description Gets the position of the container on the y axis relative to the local coordinates of the parent. This is an alias to position.y ### Method GET ### Endpoint /y ### Response #### Success Response (200) - **value** (number) - The y position of the container #### Response Example ``` 200 ``` ``` -------------------------------- ### GET /x Source: https://pixijs.download/release/docs/gif Gets the position of the container on the x axis relative to the local coordinates of the parent. This is an alias to position.x. ```APIDOC ## GET /x ### Description Gets the position of the container on the x axis relative to the local coordinates of the parent. This is an alias to position.x ### Method GET ### Endpoint /x ### Response #### Success Response (200) - **value** (number) - The x position of the container #### Response Example ``` 100 ``` ``` -------------------------------- ### Handle Right Mouse Button Up Event in PixiJS Source: https://pixijs.download/release/docs/scene This code shows how to handle the `rightup` event in PixiJS. It includes examples for both emitter and property-based handlers, which reset the sprite's scale to its original size when the right mouse button is released over the object. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('rightup', (event) => { sprite.scale.set(1.0); }); // Using property-based handler sprite.onrightup = (event) => { sprite.scale.set(1.0); }; ``` -------------------------------- ### Configure Application Options Source: https://pixijs.download/release/docs/app Comprehensive configuration covering rendering and plugin options. Specifies canvas dimensions, background color, antialiasing, device pixel ratio resolution, and renderer preference. Includes plugin settings for ticker behavior and auto-resize targets. ```javascript await app.init({ // Rendering options width: 800, // Canvas width height: 600, // Canvas height backgroundColor: 0x1099bb, // Background color antialias: true, // Enable antialiasing resolution: window.devicePixelRatio, // Screen resolution preference: 'webgl', // 'webgl' or 'webgpu' // Plugin options autoStart: true, // Start ticker automatically sharedTicker: false, // Use dedicated ticker resizeTo: window, // Auto-resize target }); ``` -------------------------------- ### Get world transform of container in PixiJS Source: https://pixijs.download/release/docs/gif Demonstrates how to retrieve the world transformation matrix of a container to get its absolute position in the scene. ```JavaScript // Get world position const worldPos = container.worldTransform; console.log(`World position: (${worldPos.tx}, ${worldPos.ty})`); ``` -------------------------------- ### Configure Animation Ticker System Source: https://pixijs.download/release/docs/app Configures TickerPlugin for frame-based animation loops. Shows initialization options for auto-start and shared instances. Provides methods to control rendering loop execution and add persistent or one-time update callbacks with access to FPS and timing data. ```javascript // Configure ticker on init await app.init({ autoStart: true, // Start ticker automatically sharedTicker: false, // Use dedicated ticker instance }); // (Optional) Start/stop the rendering loop app.start(); app.stop(); // Access ticker properties console.log(app.ticker.FPS); // Current FPS console.log(app.ticker.deltaMS); // MS since last update // Add update callbacks app.ticker.add(() => { // Animation logic here }); app.ticker.addOnce(() => { // Logic to run once after the next frame }); ``` -------------------------------- ### Get Sprite Size with Object Reuse - JavaScript Source: https://pixijs.download/release/docs/gif Retrieves the size of the Sprite as a Size object based on texture dimensions and scale. More efficient than getting width and height separately. Supports optional object reuse to avoid allocations. ```javascript // Basic size retrieval const sprite = new Sprite(Texture.from('sprite.png')); const size = sprite.getSize(); console.log(`Size: ${size.width}x${size.height}`); // Reuse existing size object const reuseSize = { width: 0, height: 0 }; sprite.getSize(reuseSize); ``` -------------------------------- ### Register PixiJS Extensions with Priority and Type Source: https://pixijs.download/release/docs/extensions Demonstrates how to register extensions in PixiJS using both object format and class-based approaches. Shows priority-based ordering, multiple extension types, and proper removal. Extensions can be registered before or after their handlers and are automatically normalized. ```javascript import { extensions, ExtensionType } from 'pixi.js'; // Register a simple object extension extensions.add({ extension: { type: ExtensionType.LoadParser, name: 'my-loader', priority: 100, // Optional priority for ordering }, // add load parser functions }); // Register a class-based extension class MyRendererPlugin { static extension = { type: [ExtensionType.WebGLSystem, ExtensionType.WebGPUSystem], name: 'myRendererPlugin' }; // add renderer plugin methods } extensions.add(MyRendererPlugin); // Remove extensions extensions.remove(MyRendererPlugin); ``` ```javascript // Register a simple extension extensions.add(MyRendererPlugin); // Register multiple extensions extensions.add( MyRendererPlugin, MySystemPlugin, }); ``` -------------------------------- ### Handle PixiJS Sprite touchstart Event Source: https://pixijs.download/release/docs/scene Explains how to handle the 'touchstart' event for a PixiJS Sprite, fired when a touch interaction begins on the screen. This can be done using either the sprite.on() method or the sprite.ontouchstart property. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('touchstart', (event) => { sprite.scale.set(0.9); }); // Using property-based handler sprite.ontouchstart = (event) => { sprite.scale.set(0.9); }; ``` -------------------------------- ### Get sprite visual bounds in PixiJS Source: https://pixijs.download/release/docs/gif Demonstrates how to retrieve the visual bounds of a sprite, accounting for texture trim areas. ```JavaScript const texture = new Texture({ source: new TextureSource({ width: 300, height: 300 }), frame: new Rectangle(196, 66, 58, 56), trim: new Rectangle(4, 4, 58, 56), orig: new Rectangle(0, 0, 64, 64), rotate: 2, }); const sprite = new Sprite(texture); const visualBounds = sprite.visualBounds; ``` -------------------------------- ### Register extensions in PixiJS Source: https://pixijs.download/release/docs/extensions Shows how to register custom extensions with PixiJS using the add method. Supports registering single or multiple extensions in one call. Extensions can be classes with static extension properties or format objects. ```javascript // Register a simple extension extensions.add(MyRendererPlugin); // Register multiple extensions extensions.add( MyRendererPlugin, MySystemPlugin, }); ``` -------------------------------- ### Debug PixiJS Visual Regression Tests Source: https://pixijs.download/release/docs/media/CONTRIBUTING Runs the visual regression tests with headful DevTools enabled, allowing for debugging and development of the test scenes. This provides more insight into rendering issues compared to the standard 'npm run test:scene'. ```bash npm run test:scene:debug ``` -------------------------------- ### Color Format Conversions in JavaScript Source: https://pixijs.download/release/docs/color Shows various methods for converting Color instances to different output formats including numeric, hexadecimal, RGB string, and object representations. Demonstrates the flexibility of the Color class for working with different color formats required by various APIs and contexts. ```JavaScript const color = new Color('red'); // Different output formats color.toNumber(); // 0xff0000 color.toHex(); // "#ff0000" color.toHexa(); // "#ff0000ff" color.toRgbString(); // "rgb(255,0,0)" color.toRgbaString(); // "rgba(255,0,0,1)" // Object representations color.toRgb(); // { r: 1, g: 0, b: 0 } color.toRgba(); // { r: 1, g: 0, b: 0, a: 1 } // Array formats color.toArray(); // [1, 0, 0, 1] color.toRgbArray(); // [1, 0, 0] ``` -------------------------------- ### Get total frames in GIF animation with PixiJS Source: https://pixijs.download/release/docs/gif Illustrates how to retrieve the total number of frames in a GIF animation using the GifSprite class. ```JavaScript // Get total frames const animation = new GifSprite({ source }); console.log('Total frames:', animation.totalFrames); ``` -------------------------------- ### Color Format Creation in JavaScript Source: https://pixijs.download/release/docs/color Demonstrates various ways to create Color instances in PixiJS using different color formats including CSS names, hexadecimal values, RGB/RGBA values, arrays, and HSL/HSLA formats. Shows the flexibility of the ColorSource type in accepting multiple input formats for consistent color handling. ```JavaScript import { Color } from 'pixi.js'; // CSS Color Names const red = new Color('red'); const blue = new Color('blue'); // Hexadecimal (Hex) const hexNumber = new Color(0xff0000); // RGB integer const hexString = new Color('#ff0000'); // 6-digit hex const shortHex = new Color('#f00'); // 3-digit hex const hexAlpha = new Color('#ff0000ff'); // 8-digit hex (with alpha) const shortHexAlpha = new Color('#f00f'); // 4-digit hex (with alpha) // RGB/RGBA Values const rgb = new Color({ r: 255, g: 0, b: 0 }); const rgba = new Color({ r: 255, g: 0, b: 0, a: 0.5 }); const rgbString = new Color('rgb(255, 0, 0)'); const rgbaString = new Color('rgba(255, 0, 0, 0.5)'); // Arrays (normalized 0-1) const rgbArray = new Color([1, 0, 0]); // RGB const rgbaArray = new Color([1, 0, 0, 0.5]); // RGBA const float32Array = new Color(new Float32Array([1, 0, 0, 0.5])); // HSL/HSLA Values const hsl = new Color({ h: 0, s: 100, l: 50 }); const hsla = new Color({ h: 0, s: 100, l: 50, a: 0.5 }); const hslString = new Color('hsl(0, 100%, 50%)'); ``` -------------------------------- ### Using Colors in PixiJS Components Source: https://pixijs.download/release/docs/color Shows how to apply colors to various PixiJS components including Sprite tinting, Graphics fill and stroke operations, and Text styling. Demonstrates the seamless integration of the Color class with different PixiJS rendering objects for consistent color management across the application. ```JavaScript import { Sprite, Graphics, Text, TextStyle } from 'pixi.js'; // Sprite tinting const sprite = Sprite.from('image.png'); sprite.tint = 'red'; // CSS color name sprite.tint = 0xff0000; // Hex number sprite.tint = '#ff0000'; // Hex string sprite.tint = new Color('red'); // Color instance // Graphics fills and strokes const graphics = new Graphics(); graphics.fill({ color: 'red' }); // CSS color name graphics.fill({ color: 0xff0000 }); // Hex number graphics.stroke({ color: '#ff0000' }); // Hex string graphics.stroke({ color: new Color('red') }); // Color instance // Text styles import { Text, TextStyle } from 'pixi.js'; const style = new TextStyle({ fill: 'red', // CSS color name // or fill: 0xff0000, // Hex number // or fill: 'rgb(255, 0, 0)', // RGB string }); const text = new Text('Hello, PixiJS!', style); ``` -------------------------------- ### Check Texture Caching State in PixiJS Source: https://pixijs.download/release/docs/gif Provides an example of how to check if a PixiJS container is currently cached as a texture using the 'isCachedAsTexture' boolean property. ```javascript // Check cache state if (container.isCachedAsTexture) { console.log('Container is cached'); } ``` -------------------------------- ### Add PixiJS Extensions Source: https://pixijs.download/release/docs/extensions Registers new extensions with PixiJS. Extensions can be provided as classes with a static 'extension' property, as extension format objects, or as multiple arguments. This function returns the extensions instance for chaining. ```javascript extensions.add(MyRendererPlugin); extensions.add( MyRendererPlugin, MySystemPlugin, ); ``` -------------------------------- ### Color Static Utilities in JavaScript Source: https://pixijs.download/release/docs/color Shows static methods and properties of the Color class including the shared instance for temporary operations and validation methods for checking color-like values. Demonstrates best practices for efficient color operations and input validation. ```JavaScript // Shared instance for temporary operations Color.shared.setValue('red').toHex(); // "#ff0000" // Check valid color values Color.isColorLike('red'); // true Color.isColorLike('#ff0000'); // true Color.isColorLike([1, 0, 0]); // true Color.isColorLike({ r: 1, g: 0, b: 0 }); // true ``` -------------------------------- ### Clean Up Application Resources Source: https://pixijs.download/release/docs/app Demonstrates proper resource cleanup to prevent memory leaks. Basic destroy() removes the application, while advanced usage accepts separate options objects for renderer and display object destruction, including recursive child cleanup and texture disposal. ```javascript // Basic cleanup app.destroy(); // Full cleanup with options app.destroy( { remove ``` -------------------------------- ### Get Child by Name in PixiJS Container Source: https://pixijs.download/release/docs/gif Retrieves a child container by its name (label). It can search recursively through the container hierarchy. This method is deprecated since version 8.0.0. ```javascript container.getChildByName('childName'); container.getChildByName(/regexName/); container.getChildByName('childName', true); ``` -------------------------------- ### Get Bounds of View in PixiJS Source: https://pixijs.download/release/docs/gif The bounds property returns the local bounds of the view in its own coordinate space. Bounds are automatically updated when the view's content changes. ```JavaScript // Get bounds dimensions const bounds = view.bounds; console.log(`Width: ${bounds.maxX - bounds.minX}`); console.log(`Height: ${bounds.maxY - bounds.minY}`); ``` -------------------------------- ### Implement Responsive Auto-Resize Source: https://pixijs.download/release/docs/app Enables automatic canvas resizing using ResizePlugin. Supports targeting the browser window or specific DOM elements. Offers manual control methods for immediate resize, throttled queued resizing, and canceling pending operations to optimize performance. ```javascript // Auto-resize to window await app.init({ resizeTo: window }); // Auto-resize to container element await app.init({ resizeTo: document.querySelector('#game') }); // Manual resize control app.resize(); // Immediate resize app.queueResize(); // Throttled resize app.cancelResize(); // Cancel pending resize ``` -------------------------------- ### Get Global Position in PixiJS Container Source: https://pixijs.download/release/docs/gif Retrieves the global position of a container, considering its hierarchy. It can optionally update a provided Point object or skip transform updates for performance. ```javascript // Basic position check const globalPos = sprite.getGlobalPosition(); console.log(`Global: (${globalPos.x}, ${globalPos.y})`); // Reuse point object const point = new Point(); sprite.getGlobalPosition(point); // Skip transform update for performance const fastPos = container.getGlobalPosition(undefined, true); ``` -------------------------------- ### Handle pointer events with FederatedPointerEvent Source: https://pixijs.download/release/docs/events Demonstrates basic and advanced pointer event handling using FederatedPointerEvent. Shows how to access pointer information, handle multi-touch interactions, process pressure and tilt data, and manage stylus-specific features. Includes event listeners for pointerdown and pointermove events with comprehensive property access and conditional stylus handling. ```typescript // Basic pointer event handling sprite.on('pointerdown', (event: FederatedPointerEvent) => { // Access pointer information console.log('Pointer ID:', event.pointerId); console.log('Pointer Type:', event.pointerType); console.log('Is Primary:', event.isPrimary); // Get pressure and tilt data console.log('Pressure:', event.pressure); console.log('Tilt:', event.tiltX, event.tiltY); // Access contact geometry console.log('Size:', event.width, event.height); }); // Handle stylus-specific features sprite.on('pointermove', (event: FederatedPointerEvent) => { if (event.pointerType === 'pen') { // Handle stylus tilt const tiltAngle = Math.atan2(event.tiltY, event.tiltX); console.log('Tilt angle:', tiltAngle); // Use barrel button pressure console.log('Tangential pressure:', event.tangentialPressure); } }); ``` -------------------------------- ### PIXI.js Pointer Movement and Position Events Source: https://pixijs.download/release/docs/scene Track pointer movement and position changes using pointermove, pointerover, and pointerout events. Enables real-time interaction based on pointer position. Uses FederatedPointerEvent for cross-platform compatibility. ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('pointermove', (event) => { sprite.position.set(event.global.x, event.global.y); }); // Using property-based handler sprite.onpointermove = (event) => { sprite.position.set(event.global.x, event.global.y); }; ``` ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('pointerover', (event) => { sprite.scale.set(1.2); }); // Using property-based handler sprite.onpointerover = (event) => { sprite.scale.set(1.2); }; ``` ```javascript const sprite = new Sprite(texture); sprite.eventMode = 'static'; // Using emitter handler sprite.on('pointerout', (event) => { sprite.scale.set(1.0); }); // Using property-based handler sprite.onpointerout = (event) => { sprite.scale.set(1.0); }; ``` -------------------------------- ### Get Child Index in PixiJS Container Source: https://pixijs.download/release/docs/gif Returns the numerical index of a specific child container within its parent. Throws an error if the child is not found. This is useful for understanding the display order. ```javascript // Basic index lookup const index = container.getChildIndex(sprite); console.log(`Sprite is at index ${index}`); // With error handling try { const index = container.getChildIndex(sprite); } catch (e) { console.warn('Child not found in container'); } ``` -------------------------------- ### Initialize Container with Children Source: https://pixijs.download/release/docs/scene Creates a PixiJS Container and initializes it with an array of child display objects. The children array is read-only, but modifications can be made using methods like `addChild` and `removeChild`. ```javascript new Container({ children: [ new Container(), // First child new Container(), // Second child ], }); ``` -------------------------------- ### Manage Scene Graph with Sprites Source: https://pixijs.download/release/docs/app Demonstrates adding display objects to the application's stage. Creates a sprite from an image asset and attaches it to the scene graph root. The stage property acts as the primary container for all visual elements. ```javascript import { Sprite } from 'pixi.js'; const sprite = Sprite.from('image.png'); app.stage.addChild(sprite); ``` -------------------------------- ### Get Global Alpha in PixiJS Container Source: https://pixijs.download/release/docs/gif Returns the compound alpha (transparency) of a container within the scene. It can either recalculate the alpha chain for accuracy or use cached values for better performance. ```javascript // Accurate but slower - recalculates entire alpha chain const preciseAlpha = container.getGlobalAlpha(); // Faster but may be outdated - uses cached alpha const cachedAlpha = container.getGlobalAlpha(true); ``` -------------------------------- ### Create Pixi.js Renderer Explicitly (WebGL/WebGPU) Source: https://pixijs.download/release/docs/rendering Allows explicit creation of either a `WebGLRenderer` or `WebGPURenderer`. After construction, the renderer must be initialized using the `init` method with optional configuration. ```javascript import { WebGLRenderer, WebGPURenderer } from 'pixi.js'; const renderer = new WebGLRenderer(); await renderer.init(options); ``` -------------------------------- ### Set Current Frame of GIF Animation in PixiJS Source: https://pixijs.download/release/docs/gif The currentFrame property gets or sets the current frame number of the GIF animation. It can be used to jump to specific frames or reset to the first frame. ```JavaScript // Get current frame const animation = new GifSprite({ source }); console.log('Current frame:', animation.currentFrame); // Jump to specific frame animation.currentFrame = 5; // Reset to first frame animation.currentFrame = 0; // Get frame at specific progress const frameAtProgress = Math.floor(animation.totalFrames * 0.5); // 50% animation.currentFrame = frameAtProgress; ``` -------------------------------- ### Get Local Bounds with Caching - JavaScript Source: https://pixijs.download/release/docs/gif Retrieves the local bounds of the container as a Bounds object. Uses cached values when possible for better performance. Subsequent calls return the same cached bounds object. ```javascript // Basic bounds check const bounds = container.getLocalBounds(); console.log(`Width: ${bounds.width}, Height: ${bounds.height}`); // subsequent calls will reuse the cached bounds const cachedBounds = container.getLocalBounds(); console.log(bounds === cachedBounds); // true ```