API Documentation official website

introduce

Pixi.js is a 2D rendering engine written in JavaScript, which can be used to make interactive graphics, animation, games and other applications in the browser. It mainly supports the WebGL API of hardware GPU rendering.

This article mainly says some basic use, because the official document is v4.5.5 version, and part of example is outdated, so use the latest version of V6.0.4 and compatible with V5.3.10 to write a demo, demo source address

use

You can do this when importing using import

import * as PIXI from 'pixi.js'
Copy the code

Some commonly used apis can be aliased to facilitate call

let Application = PIXI.Application,
    Container = PIXI.Container,
    TextureCache = PIXI.utils.TextureCache,
    Sprite = PIXI.Sprite,
    Rectangle = PIXI.Rectangle,
    Graphics = PIXI.Graphics;
Copy the code

The general process is as follows:

  1. Create a canvas
  2. Add the canvas to the correspondingdominternal
  3. Create a display object, such as text, polygons, sprites, etc
  4. Adds the display object to the stage, which defaults to the size of the internal element

A sample

let app = new PIXI.Application({width: 800.height: 800.transparent: true});

//Add the canvas that Pixi automatically created for you to the HTML document
document.body.appendChild(app.view);

// Create a text style
let style = new PIXI.TextStyle({
    fontFamily: "Arial".fontSize: 36.fill: "white".stroke: '#ff3300'.strokeThickness: 4.dropShadow: true.dropShadowColor: "# 000000".dropShadowBlur: 4.dropShadowAngle: Math.PI / 6.dropShadowDistance: 6});// Create a text display object
let message = new PIXI.Text("Hello Pixi!", style);

message.zIndex = 2

// Create a rectangle display object
let rectangle = new Graphics();
rectangle.beginFill(0x66CCFF);
rectangle.lineStyle(4.0xFF3300.0.5); // Width, color, transparency
rectangle.drawRect(2.2.64.64);
rectangle.endFill();

rectangle.zIndex = 1;

let container = new Container();
container.sortableChildren = true; // Make the child display object sortable
container.addChild(message)
container.addChild(rectangle)

app.stage.addChild(container) // Add the container to the stage
Copy the code

Stage can be understood as the container at the root, which represents the stage on the canvas. The size of the stage depends on the size of the content, rather than the entire canvas. If the content is small and the size of stage is set to the same size as the canvas, the content will be forced to enlarge, resulting in blurring. The same is true when the content is wrapped in another container.

Text and rectangles are DisplayObject, which is the base of all classes that can be rendered on the screen, and DisplayObject inherits EventEmitter. EventEmitter provides a common function for sending and receiving events

Draw a rectangle

let rectangle = new Graphics();
// Fill the color
rectangle.beginFill(0x66CCFF);
// Draw the border
rectangle.lineStyle(4.0xFF3300.0.5); // Width, color, transparency
// Define the starting coordinates of the rectangle, as well as the width and height
rectangle.drawRect(2.2.64.64);
rectangle.endFill();

app.stage.addChild(rectangle)
Copy the code

Here at 4 pixels, instead of starting with the outer outline of the element like CSS, 4 pixels will have 2 pixels outside the rectangle and 2 pixels inside the rectangle

Load a Sprite map

import imgSrc from './lion-check.png';

// ... 

app.loader.add(imgSrc).load(setup);

// A callback after the image is loaded
function setup() {
    // Add the image to the text cache
    let texture = PIXI.utils.TextureCache[imgSrc];
    let lion = new PIXI.Sprite(texture);
    app.stage.addChild(lion);
}
Copy the code

Loader code in official documentation

PIXI.loader
  .add("images/anyImage.png")
  .load(setup);
Copy the code

There is no loader in PIXI, but only in the APPLICATION instance created by Aplication

Displays the hierarchy of objects

  • Hierarchy andaddChildThe order of the calls depends, with the first inserted level being low and displayed at the bottom and the last inserted level being displayed at the top
  • You can also do this by putting these elements into acontainer, thecontainerthesortableChildrenProperty set totrueAnd then modify theirszIndexValue to change the hierarchy,zIndexThe lower the value, the lower the level

The event processing

Event types can be roughly divided into:

// Compatible with both mouse and touch screen triggers
type InteractionPointerEvents = "pointerdown" | "pointercancel" | "pointerup" | "pointertap" | "pointerupoutside" | "pointermove" | "pointerover" | "pointerout";
Copy the code
// The touch screen triggers an event
type InteractionTouchEvents = "touchstart" | "touchcancel" | "touchend" | "touchendoutside" | "touchmove" ;
Copy the code
// The mouse triggers the event
type InteractionMouseEvents = "rightdown" | "mousedown" | "rightup" | "mouseup" | "rightclick" | "click" | "rightupoutside" | "mouseupoutside" | "mousemove" | "mouseover" | "mouseout";
Copy the code
1. Bind a mouse press event to a display object

let message = new PIXI.Text("Text", style);
message.interactive = true; // Turn message into an interactive object
message.buttonMode = true; // Change the pointer to a hand shape
message.on('pointerdown'.e= > {
    // Prevent events from bubbling
    e.stopPropagation();
})
Copy the code

First make the display object interactive, setting interactive to true, otherwise the binding event will not work. ButtonMode allows interaction even if it is not set, which changes the mouse pointer to the shape of a finger clicking a button. Set CURSOR: pointer similar to the CSS.

2. Drag events

Since Pixi does not provide drag events directly, we implement them ourselves

let style = new PIXI.TextStyle({/ * * /});

let message = new PIXI.Text("I can drag.", style);
message.interactive = true;
message.buttonMode = true;
app.stage.interactive = true;

let selectedTarget;
let offsetX = 0;
let offsetY = 0;

message.on('pointerdown'.e= > {
    e.target.alpha = 0.5;
    selectedTarget = e.target;
    let { x, y } = e.data.global;
    // Calculate the mouse coordinates relative to the internal coordinates of the element, so that you can set offsets later
    offsetX = x - selectedTarget.x;
    offsetY = y - selectedTarget.y;
    app.stage.on('pointermove', onMove)
})

function onMove(e) {
    let { x, y } = e.data.global;
    let point = {
        x: x - offsetX,
        y: y - offsetY
    }
    selectedTarget.parent.toLocal(point, null, selectedTarget.position);
}
message.on('pointerup'.e= > {
    selectedTarget.alpha = 1;
    app.stage.removeListener('pointermove', onMove)
})

app.stage.addChild(message);
Copy the code

The coordinates of the mouse relative to the canvas are stored in the data.global of the event object. The official call to example is

e.global
Copy the code

Now changed to

e.data.global
Copy the code

ToLocal source is located in the display/SRC/DisplayObject. Ts

/**
 * Calculates the local position of the display object relative to another point.
 *
 * @param {PIXI.IPointData} position - The world origin to calculate from.
 * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from.
 * @param {PIXI.Point} [point] - A Point object in which to store the value, optional
 *  (otherwise will create a new Point).
 * @param {boolean} [skipUpdate=false] - Should we skip the update transform
 * @return {PIXI.Point} A point object representing the position of this object
 */
toLocal<P extends IPointData = Point>(position: IPointData, from? : DisplayObject, point? : P, skipUpdate? :boolean): P
{
    / * omit... * /
}
Copy the code

The first argument position and the third argument both take x and y information

3. Rolling events

The scrolling scheme uses pixi-ScrollBox directly, which relies on pixi-viewPort.

import img from '@/images/bg.jpg';

/* omit some code */

const scrollbox = new Scrollbox({ 
    boxWidth: 400.boxHeight: 200.fade: true.// The scroll bar disappears automatically
    divWheel: app.view,
    interaction: app.renderer.plugins.interaction // The mouse wheel cannot be detected if it is not added
})

app.loader.add(img).load(setup);

app.stage.interactive = true;

function setup() {
    let texture = PIXI.utils.TextureCache[img];
    let bg = new PIXI.Sprite(texture);
    const sprite = scrollbox.content.addChild(bg)
    sprite.width = 3840 / 4
    sprite.height = 2160 / 4
    // sprite.tint = 0xff0000
    scrollbox.update()
    app.stage.addChild(scrollbox)
}
Copy the code

The demo source code

Making the address

Give me a thumbs up at the end