Skip to content

Instantly share code, notes, and snippets.

@canadaduane
Created May 17, 2025 17:05
Show Gist options
  • Save canadaduane/2f7916c7e1465acdc216cf1a42292090 to your computer and use it in GitHub Desktop.
Save canadaduane/2f7916c7e1465acdc216cf1a42292090 to your computer and use it in GitHub Desktop.
PixiJS Guides and Docs -- llms.txt

Introduction & Overview

What PixiJS Is

So what exactly is PixiJS? At its heart, PixiJS is a rendering system that uses WebGL (or optionally Canvas) to display images and other 2D visual content. It provides a full scene graph (a hierarchy of objects to render), and provides interaction support to enable handling click and touch events. It is a natural replacement for Flash in the modern HTML5 world, but provides better performance and pixel-level effects that go beyond what Flash could achieve. It is perfect for online games, educational content, interactive ads, data visualization... any web-based application where complex graphics are important. And coupled with technology such as Cordova and Electron, PixiJS apps can be distributed beyond the browser as mobile and desktop applications.

Here's what else you get with PixiJS:

PixiJS Is ... Fast

One of the major features that distinguishes PixiJS from other web-based rendering solutions is speed. From the ground up, the render pipeline has been built to get the most performance possible out of your users' browsers. Automatic sprite and geometry batching, careful use of GPU resources, a tight scene graph - no matter your application, speed is valuable, and PixiJS has it to spare.

... More Than Just Sprites

Drawing images on a page can be handled with HTML5 and the DOM, so why use PixiJS? Beyond performance, the answer is that PixiJS goes well beyond simple images. Draw trails and tracks with MeshRope. Draw polygons, lines, circles and other primitives with Graphics. Text provides full text rendering support that's just as performant as sprites. And even when drawing simple images, PixiJS natively supports spritesheets for efficient loading and ease of development.

... Hardware accelerated

JavaScript has two APIs for handling hardware acceleration for graphical rendering: WebGL and the more modern WebGPU. Both essentially offer a JavaScript API for accessing users' GPUs for fast rendering and advanced effects. PixiJS leverages them to efficiently display thousands of moving sprites, even on mobile devices. However, using WebGL and WebGPU offers more than just speed. By using the Filter class, you can write shader programs (or use pre-built ones!) to achieve displacement maps, blurring, and other advanced visual effects that cannot be accomplished with just the DOM or Canvas APIs.

... Open Source

Want to understand how the engine works? Trying to track down a bug? Been burned by closed-source projects going dark? With PixiJS, you get a mature project with full source code access. We're MIT licensed for compatibility, and hosted on GitHub for issue tracking and ease of access.

... Extensible

Open source helps. So does being based on JavaScript. But the real reason PixiJS is easy to extend is the clean internal API that underlies every part of the system. After years of development and 5 major releases, PixiJS is ready to make your project a success, no matter what your needs.

... Easy to Deploy

Flash required the player. Unity requires an installer or app store. PixiJS requires... a browser. Deploying PixiJS on the web is exactly like deploying a web site. That's all it is - JavaScript + images + audio, like you've done a hundred times. Your users simply visit a URL, and your game or other content is ready to run. But it doesn't stop at the web. If you want to deploy a mobile app, wrap your PixiJS code in Cordova. Want to deploy a standalone desktop program? Build an Electron wrapper, and you're ready to rock.

What PixiJS Is Not

While PixiJS can do many things, there are things it can't do, or that require additional tools to accomplish. Newcomers to PixiJS often struggle to identify which tasks PixiJS can solve, and which require outside solutions. If you're about to start a project, it can be helpful to know if PixiJS is a good fit for your needs. The following list is obviously incomplete - PixiJS is also not, for example, a duck - but it includes many common tasks or features that you might expect us to support.

PixiJS Is Not ... A Framework

PixiJS is a rendering engine, and it supports additional features such as interaction management that are commonly needed when using a render engine. But it is not a framework like Unity or Phaser. Frameworks are designed to do all the things you'd need to do when building a game - user settings management, music playback, object scripting, art pipeline management... the list goes on. PixiJS is designed to do one thing really well - render graphical content. This lets us focus on keeping up with new technology, and makes downloading PixiJS blazingly fast.

... A 3D Renderer

PixiJS is built for 2D. Platformers, adventure games, interactive ads, custom data visualization... all good. But if you want to render 3D models, you might want to check out babylon.js or three.js.

... A Mobile App

If you're looking to build mobile games, you can do it with PixiJS, but you'll need to use a deployment system like Apache Cordova if you want access to native bindings. We don't provide access to the camera, location services, notifications, etc.

... A UI Library

Building a truly generic UI system is a huge challenge, as anyone who has worked with Unity's UI tools can attest. We've chosen to avoid the complexity to stay true to our core focus on speed. While you can certainly build your own UI using PixiJS's scene graph and interaction manager, we don't ship with a UI library out of the box.

... A Data Store

There are many techniques and technologies that you can use to store settings, scores, and other data. Cookies, Web Storage, server-based storage... there are many solutions, each with advantages and disadvantages. You can use any of them with PixiJS, but we don't provide tools to do so.

... An Audio Library

At least, not out of the box. Again, web audio technology is a constantly evolving challenge, with constantly changing rules and requirements across many browsers. There are a number of dedicated web audio libraries (such as Howler.js that can be used with PixiJS to play sound effects and music. Alternatively, the PixiJS Sound plugin is designed to work well with PixiJS.

... A Development Environment

There are a number of tools that are useful for building 2D art and games that you might expect to be a part of PixiJS, but we're a rendering engine, not a development environment. Packing sprite sheets, processing images, building mipmaps or Retina-ready sprites - there are great standalone tools for this type of tooling. Where appropriate throughout the guides, we'll point you to tools that may be useful.

So Is PixiJS Right For Me?

Only you know! If you're looking for a tightly focused, fast and efficient rendering engine for your next web-based project, PixiJS is likely a great fit.

If you need a full game development framework, with native bindings and a rich UI library, you may want to explore other options.

Or you may not. It can be faster and easier to build just the subset of a full framework that your project needs than it can be to digest a monolithic API with bells and whistles you don't need. There are hundreds of complex, rich games and visual projects that use PixiJS for rendering, with plugins or custom code to add the UI and sound effects. There are benefits to both approaches. Regardless, we hope you have a better feel for what PixiJS can (and cannot!) offer your project.

Getting Started

In this section we're going to build the simplest possible PixiJS application. In doing so, we'll walk through the basics of how to build and serve the code.

Advanced Users

A quick note before we start: this guide is aimed at beginning PixiJS developers who have minimal experience developing JavaScript-based applications. If you are a coding veteran, you may find that the level of detail here is not helpful. If that's the case, you may want to skim this guide, then jump into how to work with PixiJS and packers like webpack and npm.

A Note About JavaScript

One final note. The JavaScript universe is currently in transition from old-school JavaScript (ES5) to the newer ES6 flavor:

// ES5
var x = 5;
setTimeout(function() { alert(x); }, 1000);
// ES6
const x = 5;
setTimeout(() => alert(x), 1000);

ES6 brings a number of major advantages in terms of clearer syntax, better variable scoping, native class support, etc. By now, all major browsers support it. Given this, our examples in these guides will use ES6. This doesn't mean you can't use PixiJS with ES5 programs! Just mentally substitute "var" for "let/const", expand the shorter function-passing syntax, and everything will run just fine.

Components of a PixiJS Application

OK! With those notes out of the way, let's get started. There are only a few steps required to write a PixiJS application:

  • Create an HTML file
  • Serve the file with a web server
  • Load the PixiJS library
  • Create an Application
  • Add the generated view to the DOM
  • Add an image to the stage
  • Write an update loop

Let's walk through them together.

The HTML File

PixiJS is a JavaScript library that runs in a web page. So the first thing we're going to need is some HTML in a file. In a real PixiJS application, you might want to embed your display within a complex existing page, or you might want your display area to fill the whole page. For this demo, we'll build an empty page to start:

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <h1>Hello PixiJS</h1>
  </body>
</html>

Create a new folder named pixi-test, then copy and paste this HTML into a new file in the pixi-test folder named index.html.

Serving the File

You will need to run a web server to develop locally with PixiJS. Web browsers prevent loading local files (such as images and audio files) on locally loaded web pages. If you just double-click your new HTML file, you'll get an error when you try to add a sprite to the PixiJS stage.

Running a web server sounds complex and difficult, but it turns out there are a number of simple web servers that will serve this purpose. For this guide, we're going to be working with Mongoose, but you could just as easily use XAMPP or the http-server Node.js package to serve your files.

To start serving your page with Mongoose, go to the Mongoose download page and download the free server for your operating system. Mongoose defaults to serving the files in the folder it's run in, so copy the downloaded executable into the folder you created in the prior step (pixi-test). Double-click the executable, tell your operating system that you trust the file to run, and you'll have a running web server, serving your new folder.

Test that everything is working by opening your browser of choice and entering http://127.0.0.1:8080 in the location bar. (Mongoose by default serves files on port 8080.) You should see "Hello PixiJS" and nothing else. If you get an error at this step, it means you didn't name your file index.html or you mis-configured your web server.

Loading PixiJS

OK, so we have a web page, and we're serving it. But it's empty. The next step is to actually load the PixiJS library. If we were building a real application, we'd want to download a target version of PixiJS from the Pixi Github repo so that our version wouldn't change on us. But for this sample application, we'll just use the CDN version of PixiJS. Add this line to the <head> section of your index.html file:

<script src="https://pixijs.download/release/pixi.js"></script>

This will include a non-minified version of the latest version of PixiJS when your page loads, ready to be used. We use the non-minified version because we're in development. In production, you'd want to use pixi.min.js instead, which is compressed for faster download and excludes assertions and deprecation warnings that can help when building your project, but take longer to download and run.

Creating an Application

Loading the library doesn't do much good if we don't use it, so the next step is to start up PixiJS. Start by replacing the line <h1>Hello PixiJS</h1> with a script tag like so:

<script type="module">
  const app = new PIXI.Application();
  await app.init({ width: 640, height: 360 });
</script>

What we're doing here is adding a JavaScript code block, and in that block creating a new PIXI.Application instance. Application is a helper class that simplifies working with PixiJS. It creates the renderer, creates the stage, and starts a ticker for updating. In production, you'll almost certainly want to do these steps yourself for added customization and control - we'll cover doing so in a later guide. For now, the Application class is a perfect way to start playing with PixiJS without worrying about the details. The Application class also has a method init that will initialize the application with the given options. This method is asynchronous, so we use the await keyword to start our logic after the promise has completed. This is because PixiJS uses WebGPU or WebGL under the hood, and the former API asynchronous.

Adding the Canvas to the DOM

When the PIXI.Application class creates the renderer, it builds a Canvas element that it will render to. In order to see what we draw with PixiJS, we need to add this Canvas element to the web page's DOM. Append the following line to your page's script block:

  document.body.appendChild(app.canvas);

This takes the canvas created by the application (the Canvas element) and adds it to the body of your page.

Creating a Sprite

So far all we've been doing is prep work. We haven't actually told PixiJS to draw anything. Let's fix that by adding an image to be displayed.

There are a number of ways to draw images in PixiJS, but the simplest is by using a Sprite. We'll get into the details of how the scene graph works in a later guide, but for now all you need to know is that PixiJS renders a hierarchy of Containers. A Sprite is a type of Container that wraps a loaded image resource to allow drawing it, scaling it, rotating it, and so forth.

Before PixiJS can render an image, it needs to be loaded. Just like in any web page, image loading happens asynchronously. We'll talk a lot more about resource loading in later guides. For now, we can use a helper method on the PIXI.Sprite class to handle the image loading for us:

  // load the PNG asynchronously
  await PIXI.Assets.load('sample.png');
  let sprite = PIXI.Sprite.from('sample.png');

Download the sample PNG here, and save it into your pixi-test directory next to your index.html.

Adding the Sprite to the Stage

Finally, we need to add our new sprite to the stage. The stage is simply a Container that is the root of the scene graph. Every child of the stage container will be rendered every frame. By adding our sprite to the stage, we tell PixiJS's renderer we want to draw it.

  app.stage.addChild(sprite);

Writing an Update Loop

While you can use PixiJS for static content, for most projects you'll want to add animation. Our sample app is actually cranking away, rendering the same sprite in the same place multiple times a second. All we have to do to make the image move is to update its attributes once per frame. To do this, we want to hook into the application's ticker. A ticker is a PixiJS object that runs one or more callbacks each frame. Doing so is surprisingly easy. Add the following to the end of your script block:

  // Add a variable to count up the seconds our demo has been running
  let elapsed = 0.0;
  // Tell our application's ticker to run a new callback every frame, passing
  // in the amount of time that has passed since the last tick
  app.ticker.add((ticker) => {
    // Add the time to our total elapsed time
    elapsed += ticker.deltaTime;
    // Update the sprite's X position based on the cosine of our elapsed time.  We divide
    // by 50 to slow the animation down a bit...
    sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0;
  });

All you need to do is to call app.ticker.add(...), pass it a callback function, and then update your scene in that function. It will get called every frame, and you can move, rotate etc. whatever you'd like to drive your project's animations.

Putting It All Together

That's it! The simplest PixiJS project!

Here's the whole thing in one place. Check your file and make sure it matches if you're getting errors.

<!doctype html>
<html>
  <head>
    <script src="https://pixijs.download/release/pixi.min.js"></script>
  </head>
  <body>
    <script type="module">
      // Create the application helper and add its render target to the page
      const app = new PIXI.Application();
      await app.init({ width: 640, height: 360 })
      document.body.appendChild(app.canvas);

      // Create the sprite and add it to the stage
      await PIXI.Assets.load('sample.png');
      let sprite = PIXI.Sprite.from('sample.png');
      app.stage.addChild(sprite);

      // Add a ticker callback to move the sprite back and forth
      let elapsed = 0.0;
      app.ticker.add((ticker) => {
        elapsed += ticker.deltaTime;
        sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0;
      });
    </script>
  </body>
</html>

Once you have things working, the next thing to do is to read through the rest of the Basics guides to dig into how all this works in much greater depth.

FAQ

What is PixiJS for?

Everything! Pixi.js is a rendering library that will allow you to create rich, interactive graphic experiences, cross-platform applications, and games without having to dive into the WebGL API or grapple with the intricacies of browser and device compatibility. Killer performance with a clean API, means not only will your content be better - but also faster to build!

Is PixiJS free?

PixiJS is and always will be free and Open Source. That said, financial contributions are what make it possible to push PixiJS further, faster. Contributions allow us to commission the PixiJS developer community to accelerate feature development and create more in-depth documentation. Support Us by making a contribution via Open Collective. Go on! It will be a massive help AND make you feel good about yourself, win win ;)

Where do I get it?

Visit our GitHub page to download the very latest version of PixiJS. This is the most up-to-date resource for PixiJS and should always be your first port of call to make sure you are using the latest version. Just click the 'Download' link in the navigation.

How do I get started?

Right here! Take a look through the Resources section for a wealth of information including documentation, forums, tutorials and the Goodboy blog.

Why should I use PixiJS?

Because you care about speed. PixiJS' #1 mantra has always been speed. We really do feel the need! We do everything we can to make PixiJS as streamlined, efficient and fast as possible, whilst balancing it with offering as many crucial and valuable features as we can.

Is PixiJS a game engine?

No. PixiJS is what we've come to think of as a "creation engine". Whilst it is extremely good for making games, the core essence of PixiJS is simply moving things around on screens as quickly and efficiently as possible. It does of course happen that it is absolutely brilliant for making games though!

Who makes PixiJS?

Outside of the highly active PixiJS community, it is primarily maintained by Mat Groves, Technical Partner of our creative agency Goodboy Digital. One of the huge advantages of creating PixiJS within the framework of a working agency is that it means its features are always driven by genuine industry demands and critically are always trialled "in anger" in our cutting-edge games, sites and apps.

I found a bug. What should I do?

Two things - lets us know via the PixiJS GitHub community and even better yet, if you know how, post a fix! Our Community is stronger in numbers so we're always keen to welcome new contributors into the team to help us shape what PixiJS becomes next.

Architecture Overview

OK, now that you've gotten a feel for how easy it is to build a PixiJS application, let's get into the specifics. For the rest of the Basics section, we're going to work from the high level down to the details. We'll start with an overview of how PixiJS is put together.

The Code

Before we get into how the code is laid out, let's talk about where it lives. PixiJS is an open source product hosted on GitHub. Like any GitHub repo, you can browse and download the raw source files for each PixiJS class, as well as search existing issues & bugs, and even submit your own. PixiJS is written in a JavaScript variant called TypeScript, which enables type-checking in JavaScript via a pre-compile step.

The Components

Here's a list of the major components that make up PixiJS. Note that this list isn't exhaustive. Additionally, don't worry too much about how each component works. The goal here is to give you a feel for what's under the hood as we start exploring the engine.

Major Components

Component Description
Renderer The core of the PixiJS system is the renderer, which displays the scene graph and draws it to the screen. PixiJS will automatically determine whether to provide you the WebGPU or WebGL renderer under the hood.
Container Main scene object which creates a scene graph: the tree of renderable objects to be displayed, such as sprites, graphics and text. See Scene Graph for more details.
Assets The Asset system provides tools for asynchronously loading resources such as images and audio files.
Ticker Tickers provide periodic callbacks based on a clock. Your game update logic will generally be run in response to a tick once per frame. You can have multiple tickers in use at one time.
Application The Application is a simple helper that wraps a Loader, Ticker and Renderer into a single, convenient easy-to-use object. Great for getting started quickly, prototyping and building simple projects.
Events PixiJS supports pointer-based interaction - making objects clickable, firing hover events, etc.
Accessibility Woven through our display system is a rich set of tools for enabling keyboard and screen-reader accessibility.

Core Concepts

Render Loop

Now that you understand the major parts of the system, let's look at how these parts work together to get your project onto the screen. Unlike a web page, PixiJS is constantly updating and re-drawing itself, over and over. You update your objects, then PixiJS renders them to the screen, then the process repeats. We call this cycle the render loop.

The majority of any PixiJS project is contained in this update + render cycle. You code the updates, PixiJS handles the rendering.

Let's walk through what happens each frame of the render loop. There are three main steps.

Running Ticker Callbacks

The first step is to calculate how much time has elapsed since the last frame, and then call the Application object's ticker callbacks with that time delta. This allows your project's code to animate and update the sprites, etc. on the stage in preparation for rendering.

Updating the Scene Graph

We'll talk a lot more about what a scene graph is and what it's made of in the next guide, but for now, all you need to know is that it contains the things you're drawing - sprites, text, etc. - and that these objects are in a tree-like hierarchy. After you've updated your game objects by moving, rotating and so forth, PixiJS needs to calculate the new positions and state of every object in the scene, before it can start drawing.

Rendering the Scene Graph

Now that our game's state has been updated, it's time to draw it to the screen. The rendering system starts with the root of the scene graph (app.stage), and starts rendering each object and its children, until all objects have been drawn. No culling or other cleverness is built into this process. If you have lots of objects outside of the visible portion of the stage, you'll want to investigate disabling them as an optimization.

Frame Rates

A note about frame rates. The render loop can't be run infinitely fast - drawing things to the screen takes time. In addition, it's not generally useful to have a frame updated more than once per screen update (commonly 60fps, but newer monitors can support 144fps and up). Finally, PixiJS runs in the context of a web browser like Chrome or Firefox. The browser itself has to balance the needs of various internal operations with servicing any open tabs. All this to say, determining when to draw a frame is a complex issue.

In cases where you want to adjust that behavior, you can set the minFPS and maxFPS attributes on a Ticker to give PixiJS hints as to the range of tick speeds you want to support. Just be aware that due to the complex environment, your project cannot guarantee a given FPS. Use the passed ticker.deltaTime value in your ticker callbacks to scale any animations to ensure smooth playback.

Custom Render Loops

What we've just covered is the default render loop provided out of the box by the Application helper class. There are many other ways of creating a render loop that may be helpful for advanced users looking to solve a given problem. While you're prototyping and learning PixiJS, sticking with the Application's provided system is the recommended approach.

Scene Graph

Every frame, PixiJS is updating and then rendering the scene graph. Let's talk about what's in the scene graph, and how it impacts how you develop your project. If you've built games before, this should all sound very familiar, but if you're coming from HTML and the DOM, it's worth understanding before we get into specific types of objects you can render.

The Scene Graph Is a Tree

The scene graph's root node is a container maintained by the application, and referenced with app.stage. When you add a sprite or other renderable object as a child to the stage, it's added to the scene graph and will be rendered and interactable. PixiJS Containers can also have children, and so as you build more complex scenes, you will end up with a tree of parent-child relationships, rooted at the app's stage.

(A helpful tool for exploring your project is the Pixi.js devtools plugin for Chrome, which allows you to view and manipulate the scene graph in real time as it's running!)

Parents and Children

When a parent moves, its children move as well. When a parent is rotated, its children are rotated too. Hide a parent, and the children will also be hidden. If you have a game object that's made up of multiple sprites, you can collect them under a container to treat them as a single object in the world, moving and rotating as one.

Each frame, PixiJS runs through the scene graph from the root down through all the children to the leaves to calculate each object's final position, rotation, visibility, transparency, etc. If a parent's alpha is set to 0.5 (making it 50% transparent), all its children will start at 50% transparent as well. If a child is then set to 0.5 alpha, it won't be 50% transparent, it will be 0.5 x 0.5 = 0.25 alpha, or 75% transparent. Similarly, an object's position is relative to its parent, so if a parent is set to an x position of 50 pixels, and the child is set to an x position of 100 pixels, it will be drawn at a screen offset of 150 pixels, or 50 + 100.

Here's an example. We'll create three sprites, each a child of the last, and animate their position, rotation, scale and alpha. Even though each sprite's properties are set to the same values, the parent-child chain amplifies each change:

// Create the application helper and add its render target to the page
const app = new Application();
await app.init({ width: 640, height: 360 })
document.body.appendChild(app.canvas);

// Add a container to center our sprite stack on the page
const container = new Container({
  x:app.screen.width / 2,
  y:app.screen.height / 2
});

app.stage.addChild(container);

// load the texture
await Assets.load('assets/images/sample.png');

// Create the 3 sprites, each a child of the last
const sprites = [];
let parent = container;
for (let i = 0; i < 3; i++) {
  let wrapper = new Container();
  let sprite = Sprite.from('assets/images/sample.png');
  sprite.anchor.set(0.5);
  wrapper.addChild(sprite);
  parent.addChild(wrapper);
  sprites.push(wrapper);
  parent = wrapper;
}

// Set all sprite's properties to the same value, animated over time
let elapsed = 0.0;
app.ticker.add((delta) => {
  elapsed += delta.deltaTime / 60;
  const amount = Math.sin(elapsed);
  const scale = 1.0 + 0.25 * amount;
  const alpha = 0.75 + 0.25 * amount;
  const angle = 40 * amount;
  const x = 75 * amount;
  for (let i = 0; i < sprites.length; i++) {
    const sprite = sprites[i];
    sprite.scale.set(scale);
    sprite.alpha = alpha;
    sprite.angle = angle;
    sprite.x = x;
  }
});

The cumulative translation, rotation, scale and skew of any given node in the scene graph is stored in the object's worldTransform property. Similarly, the cumulative alpha value is stored in the worldAlpha property.

Render Order

So we have a tree of things to draw. Who gets drawn first?

PixiJS renders the tree from the root down. At each level, the current object is rendered, then each child is rendered in order of insertion. So the second child is rendered on top of the first child, and the third over the second.

Check out this example, with two parent objects A & D, and two children B & C under A:

// Create the application helper and add its render target to the page
const app = new Application();
await app.init({ width: 640, height: 360 })
document.body.appendChild(app.canvas);

// Label showing scene graph hierarchy
const label = new Text({
  text:'Scene Graph:\n\napp.stage\n  ┗ A\n     ┗ B\n     ┗ C\n  ┗ D',
  style:{fill: '#ffffff'},
  position: {x: 300, y: 100}
});

app.stage.addChild(label);

// Helper function to create a block of color with a letter
const letters = [];
function addLetter(letter, parent, color, pos) {
  const bg = new Sprite(Texture.WHITE);
  bg.width = 100;
  bg.height = 100;
  bg.tint = color;

  const text = new Text({
    text:letter,
    style:{fill: "#ffffff"}
  });

  text.anchor.set(0.5);
  text.position = {x: 50, y: 50};

  const container = new Container();
  container.position = pos;
  container.visible = false;
  container.addChild(bg, text);
  parent.addChild(container);

  letters.push(container);
  return container;
}

// Define 4 letters
let a = addLetter('A', app.stage, 0xff0000, {x: 100, y: 100});
let b = addLetter('B', a,         0x00ff00, {x: 20,  y: 20});
let c = addLetter('C', a,         0x0000ff, {x: 20,  y: 40});
let d = addLetter('D', app.stage, 0xff8800, {x: 140, y: 100});

// Display them over time, in order
let elapsed = 0.0;
app.ticker.add((ticker) => {
  elapsed += ticker.deltaTime / 60.0;
  if (elapsed >= letters.length) { elapsed = 0.0; }
  for (let i = 0; i < letters.length; i ++) {
    letters[i].visible = elapsed >= i;
  }
});

If you'd like to re-order a child object, you can use setChildIndex(). To add a child at a given point in a parent's list, use addChildAt(). Finally, you can enable automatic sorting of an object's children using the sortableChildren option combined with setting the zIndex property on each child.

RenderGroups

As you delve deeper into PixiJS, you'll encounter a powerful feature known as Render Groups. Think of Render Groups as specialized containers within your scene graph that act like mini scene graphs themselves. Here's what you need to know to effectively use Render Groups in your projects. For more info check out the RenderGroups overview

Culling

If you're building a project where a large proportion of your scene objects are off-screen (say, a side-scrolling game), you will want to cull those objects. Culling is the process of evaluating if an object (or its children!) is on the screen, and if not, turning off rendering for it. If you don't cull off-screen objects, the renderer will still draw them, even though none of their pixels end up on the screen.

PixiJS doesn't provide built-in support for viewport culling, but you can find 3rd party plugins that might fit your needs. Alternately, if you'd like to build your own culling system, simply run your objects during each tick and set renderable to false on any object that doesn't need to be drawn.

Local vs Global Coordinates

If you add a sprite to the stage, by default it will show up in the top left corner of the screen. That's the origin of the global coordinate space used by PixiJS. If all your objects were children of the stage, that's the only coordinates you'd need to worry about. But once you introduce containers and children, things get more complicated. A child object at [50, 100] is 50 pixels right and 100 pixels down from its parent.

We call these two coordinate systems "global" and "local" coordinates. When you use position.set(x, y) on an object, you're always working in local coordinates, relative to the object's parent.

The problem is, there are many times when you want to know the global position of an object. For example, if you want to cull offscreen objects to save render time, you need to know if a given child is outside the view rectangle.

To convert from local to global coordinates, you use the toGlobal() function. Here's a sample usage:

// Get the global position of an object, relative to the top-left of the screen
let globalPos = obj.toGlobal(new Point(0,0));

This snippet will set globalPos to be the global coordinates for the child object, relative to [0, 0] in the global coordinate system.

Global vs Screen Coordinates

When your project is working with the host operating system or browser, there is a third coordinate system that comes into play - "screen" coordinates (aka "viewport" coordinates). Screen coordinates represent position relative to the top-left of the canvas element that PixiJS is rendering into. Things like the DOM and native mouse click events work in screen space.

Now, in many cases, screen space is equivalent to world space. This is the case if the size of the canvas is the same as the size of the render view specified when you create you Application. By default, this will be the case - you'll create for example an 800x600 application window and add it to your HTML page, and it will stay that size. 100 pixels in world coordinates will equal 100 pixels in screen space. BUT! It is common to stretch the rendered view to have it fill the screen, or to render at a lower resolution and up-scale for speed. In that case, the screen size of the canvas element will change (e.g. via CSS), but the underlying render view will not, resulting in a mis-match between world coordinates and screen coordinates.

Key Components

Containers

The Container class provides a simple display object that does what its name implies - collect a set of child objects together. But beyond grouping objects, containers have a few uses that you should be aware of.

Commonly Used Attributes

The most common attributes you'll use when laying out and animating content in PixiJS are provided by the Container class:

Property Description
position X- and Y-position are given in pixels and change the position of the object relative to its parent, also available directly as object.x / object.y
rotation Rotation is specified in radians, and turns an object clockwise (0.0 - 2 * Math.PI)
angle Angle is an alias for rotation that is specified in degrees instead of radians (0.0 - 360.0)
pivot Point the object rotates around, in pixels - also sets origin for child objects
alpha Opacity from 0.0 (fully transparent) to 1.0 (fully opaque), inherited by children
scale Scale is specified as a percent with 1.0 being 100% or actual-size, and can be set independently for the x and y axis
skew Skew transforms the object in x and y similar to the CSS skew() function, and is specified in radians
visible Whether the object is visible or not, as a boolean value - prevents updating and rendering object and children
renderable Whether the object should be rendered - when false, object will still be updated, but won't be rendered, doesn't affect children

Containers as Groups

Almost every type of display object is also derived from Container! This means that in many cases you can create a parent-child hierarchy with the objects you want to render.

However, it's a good idea not to do this. Standalone Container objects are very cheap to render, and having a proper hierarchy of Container objects, each containing one or more renderable objects, provides flexibility in rendering order. It also future-proofs your code, as when you need to add an additional object to a branch of the tree, your animation logic doesn't need to change - just drop the new object into the proper Container, and your logic moves the Container with no changes to your code.

So that's the primary use for Containers - as groups of renderable objects in a hierarchy.

Check out the container example code.

Masking

Another common use for Container objects is as hosts for masked content. "Masking" is a technique where parts of your scene graph are only visible within a given area.

Think of a pop-up window. It has a frame made of one or more Sprites, then has a scrollable content area that hides content outside the frame. A Container plus a mask makes that scrollable area easy to implement. Add the Container, set its mask property to a Graphics object with a rect, and add the text, image, etc. content you want to display as children of that masked Container. Any content that extends beyond the rectangular mask will simply not be drawn. Move the contents of the Container to scroll as desired.

// Create the application helper and add its render target to the page
let app = new Application({ width: 640, height: 360 });
document.body.appendChild(app.view);

// Create window frame
let frame = new Graphics({
  x:320 - 104,
  y:180 - 104
})
.rect(0, 0, 208, 208)
.fill(0x666666)
.stroke({ color: 0xffffff, width: 4, alignment: 0 })

app.stage.addChild(frame);

// Create a graphics object to define our mask
let mask = new Graphics()
// Add the rectangular area to show
 .rect(0,0,200,200)
 .fill(0xffffff);

// Add container that will hold our masked content
let maskContainer = new Container();
// Set the mask to use our graphics object from above
maskContainer.mask = mask;
// Add the mask as a child, so that the mask is positioned relative to its parent
maskContainer.addChild(mask);
// Offset by the window's frame width
maskContainer.position.set(4,4);
// And add the container to the window!
frame.addChild(maskContainer);

// Create contents for the masked container
let text = new Text({
  text:'This text will scroll up and be masked, so you can see how masking works.  Lorem ipsum and all that.\n\n' +
  'You can put anything in the container and it will be masked!',
  style:{
    fontSize: 24,
    fill: 0x1010ff,
    wordWrap: true,
    wordWrapWidth: 180
  },
  x:10
});

maskContainer.addChild(text);

// Add a ticker callback to scroll the text up and down
let elapsed = 0.0;
app.ticker.add((ticker) => {
  // Update the text's y coordinate to scroll it
  elapsed += ticker.deltaTime;
  text.y = 10 + -100.0 + Math.cos(elapsed/50.0) * 100.0;
});

There are two types of masks supported by PixiJS:

Use a Graphics object to create a mask with an arbitrary shape - powerful, but doesn't support anti-aliasing

Sprite: Use the alpha channel from a Sprite as your mask, providing anti-aliased edging - not supported on the Canvas renderer

Filtering

Another common use for Container objects is as hosts for filtered content. Filters are an advanced, WebGL/WebGPU-only feature that allows PixiJS to perform per-pixel effects like blurring and displacements. By setting a filter on a Container, the area of the screen the Container encompasses will be processed by the filter after the Container's contents have been rendered.

Below are list of filters available by default in PixiJS. There is, however, a community repository with many more filters.

Filter Description
AlphaFilter Similar to setting alpha property, but flattens the Container instead of applying to children individually.
BlurFilter Apply a blur effect
ColorMatrixFilter A color matrix is a flexible way to apply more complex tints or color transforms (e.g., sepia tone).
DisplacementFilter Displacement maps create visual offset pixels, for instance creating a wavy water effect.
NoiseFilter Create random noise (e.g., grain effect).

Under the hood, each Filter we offer out of the box is written in both glsl (for WebGL) and wgsl (for WebGPU). This means all filters should work on both renderers.

Important: Filters should be used somewhat sparingly. They can slow performance and increase memory usage if used too often in a scene.

Sprites

Sprites are the simplest and most common renderable object in PixiJS. They represent a single image to be displayed on the screen. Each Sprite contains a Texture to be drawn, along with all the transformation and display state required to function in the scene graph.

Creating Sprites

To create a Sprite, all you need is a Texture (check out the Texture guide). Load a PNG's URL using the Assets class, then call Sprite.from(url) and you're all set. Unlike v7 you now must load your texture before using it, this is to ensure best practices.

Check out the sprite example code.

Using Sprites

In our Container guide, we learned about the Container class and the various properties it defines. Since Sprite objects are also containers, you can move a sprite, rotate it, and update any other display property.

Alpha, Tint and Blend Modes

Alpha is a standard display object property. You can use it to fade sprites into the scene by animating each sprite's alpha from 0.0 to 1.0 over a period of time.

Tinting allows you to multiply the color value of every pixel by a single color. For example, if you had a dungeon game, you might show a character's poison status by setting obj.tint = 0x00FF00, which would give a green tint to the character.

Blend modes change how pixel colors are added to the screen when rendering. The three main modes are add, which adds each pixel's RGB channels to whatever is under your sprite (useful for glows and lighting), multiply which works like tint, but on a per-pixel basis, and screen, which overlays the pixels, brightening whatever is underneath them.

Scale vs Width & Height

One common area of confusion when working with sprites lies in scaling and dimensions. The Container class allows you to set the x and y scale for any object. Sprites, being Containers, also support scaling. In addition, however, Sprites support explicit width and height attributes that can be used to achieve the same effect, but are in pixels instead of a percentage. This works because a Sprite object owns a Texture, which has an explicit width and height. When you set a Sprite's width, internally PixiJS converts that width into a percentage of the underlying texture's width and updates the object's x-scale. So width and height are really just convenience methods for changing scale, based on pixel dimensions rather than percentages.

Pivot vs Anchor

If you add a sprite to your stage and rotate it, it will by default rotate around the top-left corner of the image. In some cases, this is what you want. In many cases, however, what you want is for the sprite to rotate around the center of the image it contains, or around an arbitrary point.

There are two ways to achieve this: pivots and anchors

An object's pivot is an offset, expressed in pixels, from the top-left corner of the Sprite. It defaults to (0, 0). If you have a Sprite whose texture is 100px x 50px, and want to set the pivot point to the center of the image, you'd set your pivot to (50, 25) - half the width, and half the height. Note that pivots can be set outside of the image, meaning the pivot may be less than zero or greater than the width/height. This can be useful in setting up complex animation hierarchies, for example. Every Container has a pivot.

An anchor, in contrast, is only available for Sprites. Anchors are specified in percentages, from 0.0 to 1.0, in each dimension. To rotate around the center point of a texture using anchors, you'd set your Sprite's anchor to (0.5, 0.5) - 50% in width and height. While less common, anchors can also be outside the standard 0.0 - 1.0 range.

The nice thing about anchors is that they are resolution and dimension agnostic. If you set your Sprite to be anchored in the middle then later change the size of the texture, your object will still rotate correctly. If you had instead set a pivot using pixel-based calculations, changing the texture size would require changing your pivot point.

So, generally speaking, you'll want to use anchors when working with Sprites.

One final note: unlike CSS, where setting the transform-origin of the image doesn't move it, in PixiJS setting an anchor or pivot will move your object on the screen. In other words, setting an anchor or pivot affects not just the rotation origin, but also the position of the sprite relative to its parent.

Textures

We're slowly working our way down from the high level to the low. We've talked about the scene graph, and in general about display objects that live in it. We're about to get to sprites and other simple display objects. But before we do, we need to talk about textures.

In PixiJS, textures are one of the core resources used by display objects. A texture, broadly speaking, represents a source of pixels to be used to fill in an area on the screen. The simplest example is a sprite - a rectangle that is completely filled with a single texture. But things can get much more complex.

Life-cycle of a Texture

Let's examine how textures really work, by following the path your image data travels on its way to the screen.

Here's the flow we're going to follow: Source Image > Loader > BaseTexture > Texture

Serving the Image

To start with, you have the image you want to display. The first step is to make it available on your server. This may seem obvious, but if you're coming to PixiJS from other game development systems, it's worth remembering that everything has to be loaded over the network. If you're developing locally, please be aware that you must use a webserver to test, or your images won't load due to how browsers treat local file security.

Loading the Image

To work with the image, the first step is to pull the image file from your webserver into the user's web browser. To do this, we can use Assets.load('myTexture.png'). Assets wraps and deals with telling the browser to fetch the image, convert it and then let you know when that has been completed. This process is asynchronous - you request the load, then time passes, then a promise completes to let you know the load is completed. We'll go into the loader in a lot more depth in a later guide.

const texture = await Assets.load('myTexture.png');

// pass a texture explicitly
const sprite = new Sprite(texture);
// as options
const sprite2 = new Sprite({texture});
// from the cache as the texture is loaded
const sprite3 = Sprite.from('myTexture.png')

TextureSources Own the Data

Once the texture has loaded, the loaded <IMG> element contains the pixel data we need. But to use it to render something, PixiJS has to take that raw image file and upload it to the GPU. This brings us to the real workhorse of the texture system - the TextureSource class. Each TextureSource manages a single pixel source - usually an image, but can also be a Canvas or Video element. TextureSources allow PixiJS to convert the image to pixels and use those pixels in rendering. In addition, it also contains settings that control how the texture data is rendered, such as the wrap mode (for UV coordinates outside the 0.0-1.0 range) and scale mode (used when scaling a texture).

TextureSource are automatically cached, so that calling Texture.from() repeatedly for the same URL returns the same TextureSource each time. Destroying a TextureSource frees the image data associated with it.

Textures are a View on BaseTextures

So finally, we get to the Texture class itself! At this point, you may be wondering what the Texture object does. After all, the BaseTexture manages the pixels and render settings. And the answer is, it doesn't do very much. Textures are light-weight views on an underlying BaseTexture. Their main attribute is the source rectangle within the TextureSource from which to pull.

If all PixiJS drew were sprites, that would be pretty redundant. But consider SpriteSheets. A SpriteSheet is a single image that contains multiple sprite images arranged within. In a Spritesheet object, a single TextureSource is referenced by a set of Textures, one for each source image in the original sprite sheet. By sharing a single TextureSource, the browser only downloads one file, and our batching renderer can blaze through drawing sprites since they all share the same underlying pixel data. The SpriteSheet's Textures pull out just the rectangle of pixels needed by each sprite.

That is why we have both Textures and TextureSource - to allow sprite sheets, animations, button states, etc to be loaded as a single image, while only displaying the part of the master image that is needed.

Loading Textures

We will discuss resource loading in a later guide, but one of the most common issues new users face when building a PixiJS project is how best to load their textures.

here's a quick cheat sheet of one good solution:

  1. Show a loading image
  2. Use Assets to ensure that all textures are loaded
  3. optionally update your loading image based on progress callbacks
  4. On loader completion, run all objects and use Texture.from() to pull the loaded textures out of the texture cache
  5. Prepare your textures (optional - see below)
  6. Hide your loading image, start rendering your scene graph

Using this workflow ensures that your textures are pre-loaded, to prevent pop-in, and is relatively easy to code.

Regarding preparing textures: Even after you've loaded your textures, the images still need to be pushed to the GPU and decoded. Doing this for a large number of source images can be slow and cause lag spikes when your project first loads. To solve this, you can use the Prepare plugin, which allows you to pre-load textures in a final step before displaying your project.

Unloading Textures

Once you're done with a Texture, you may wish to free up the memory (both WebGL-managed buffers and browser-based) that it uses. To do so, you should call destroy() on the BaseTexture that owns the data. Remember that Textures don't manage pixel data!

This is a particularly good idea for short-lived imagery like cut-scenes that are large and will only be used once. If a texture is destroyed that was loaded via Assets then the assets class will automatically remove it from the cache for you.

Beyond Images

As we alluded to above, you can make a Texture out of more than just images:

Video: Pass an HTML5 <VIDEO> element to TextureSource.from() to allow you to display video in your project. Since it's a texture, you can tint it, add filters, or even apply it to custom geometry.

Canvas: Similarly, you can wrap an HTML5 <CANVAS> element in a BaseTexture to let you use canvas's drawing methods to dynamically create a texture.

SVG: Pass in an <SVG> element or load a .svg URL, and PixiJS will attempt to rasterize it. For highly network-constrained projects, this can allow for beautiful graphics with minimal network load times.

RenderTexture: A more advanced (but very powerful!) feature is to build a Texture from a RenderTexture. This can allow for building complex geometry using a Geometry object, then baking that geometry down to a simple texture.

Each of these texture sources has caveats and nuances that we can't cover in this guide, but they should give you a feeling for the power of PixiJS's texture system.

Check out the render texture example code.

Spritesheets

Now that you understand basic sprites, it's time to talk about a better way to create them - the Spritesheet class.

A Spritesheet is a media format for more efficiently downloading and rendering Sprites. While somewhat more complex to create and use, they are a key tool in optimizing your project.

Anatomy of a Spritesheet

The basic idea of a spritesheet is to pack a series of images together into a single image, track where each source image ends up, and use that combined image as a shared BaseTexture for the resulting Sprites.

The first step is to collect the images you want to combine. The sprite packer then collects the images, and creates a new combined image.

As this image is being created, the tool building it keeps track of the location of the rectangle where each source image is stored. It then writes out a JSON file with that information.

These two files, in combination, can be passed into a SpriteSheet constructor. The SpriteSheet object then parses the JSON, and creates a series of Texture objects, one for each source image, setting the source rectangle for each based on the JSON data. Each texture uses the same shared BaseTexture as its source.

Doubly Efficient

SpriteSheets help your project in two ways.

First, by speeding up the loading process. While downloading a SpriteSheet's texture requires moving the same (or even slightly more!) number of bytes, they're grouped into a single file. This means that the user's browser can request and download far fewer files for the same number of Sprites. The number of files itself is a key driver of download speed, because each request requires a round-trip to the webserver, and browsers are limited to how many files they can download simultaneously. Converting a project from individual source images to shared sprite sheets can cut your download time in half, at no cost in quality.

Second, by improving batch rendering. WebGL rendering speed scales roughly with the number of draw calls made. Batching multiple Sprites, etc. into a single draw call is the main secret to how PixiJS can run so blazingly fast. Maximizing batching is a complex topic, but when multiple Sprites all share a common BaseTexture, it makes it more likely that they can be batched together and rendered in a single call.

Creating SpriteSheets

You can use a 3rd party tool to assemble your sprite sheet files. Here are two that may fit your needs:

ShoeBox: ShoeBox is a free, Adobe AIR-based sprite packing utility that is great for small projects or learning how SpriteSheets work.

TexturePacker: TexturePacker is a more polished tool that supports advanced features and workflows. A free version is available which has all the necessary features for packing spritesheets for PixiJS. It's a good fit for larger projects and professional game development, or projects that need more complex tile mapping features.

Spritesheet data can also be created manually or programmatically, and supplied to a new AnimatedSprite. This may be an easier option if your sprites are already contained in a single image.

// Create object to store sprite sheet data
const atlasData = {
	frames: {
		enemy1: {
			frame: { x: 0, y:0, w:32, h:32 },
			sourceSize: { w: 32, h: 32 },
			spriteSourceSize: { x: 0, y: 0, w: 32, h: 32 }
		},
		enemy2: {
			frame: { x: 32, y:0, w:32, h:32 },
			sourceSize: { w: 32, h: 32 },
			spriteSourceSize: { x: 0, y: 0, w: 32, h: 32 }
		},
	},
	meta: {
		image: 'images/spritesheet.png',
		format: 'RGBA8888',
		size: { w: 128, h: 32 },
		scale: 1
	},
	animations: {
		enemy: ['enemy1','enemy2'] //array of frames by name
	}
}


// Create the SpriteSheet from data and image
const spritesheet = new Spritesheet(
	Texture.from(atlasData.meta.image),
	atlasData
);

// Generate all the Textures asynchronously
await spritesheet.parse();

// spritesheet is ready to use!
const anim = new AnimatedSprite(spritesheet.animations.enemy);

// set the animation speed
anim.animationSpeed = 0.1666;
// play the animation on a loop
anim.play();
// add it to the stage to render
app.stage.addChild(anim);

Assets

The Assets package

The Assets package is a modern replacement for the old Loader class. It is a promise-based resource management solution that will download, cache and parse your assets into something you can use. The downloads can be simultaneous and in the background, meaning faster startup times for your app, the cache ensures that you never download the same asset twice and the extensible parser system allows you to easily extend and customize the process to your needs.

Getting started

Assets relies heavily on JavaScript Promises that all modern browsers support, however, if your target browser doesn't support promises you should look into polyfilling them.

Making our first Assets Promise

To quickly use the Assets instance, you just need to call Assets.load and pass in an asset. This will return a promise that when resolved will yield the value you seek. In this example, we will load a texture and then turn it into a sprite.

import { Application, Assets, Sprite } from 'pixi.js';

// 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);

// Start loading right away and create a promise
const texturePromise = Assets.load('https://pixijs.com/assets/bunny.png');

// When the promise resolves, we have the texture!
texturePromise.then((resolvedTexture) =>
{
    // create a new Sprite from the resolved loaded Texture
    const bunny = Sprite.from(resolvedTexture);

    // 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);
});

One very important thing to keep in mind while using Assets is that all requests are cached and if the URL is the same, the promise returned will also be the same. To show it in code:

promise1 = Assets.load('bunny.png')
promise2 = Assets.load('bunny.png')
// promise1 === promise2

Out of the box, the following assets types can be loaded without the need for external plugins:

  • Textures (avif, webp, png, jpg, gif)
  • Sprite sheets (json)
  • Bitmap fonts (xml, fnt, txt)
  • Web fonts (ttf, woff, woff2)
  • Json files (json)
  • Text files (txt)

More types can be added fairly easily by creating additional loader parsers.

Working with unrecognizable URLs

With the basic syntax, asset types are recognized by their file extension - for instance https://pixijs.com/assets/bunny.png ends with .png so Assets.load can figure it should use the texture loader.

In some cases you may not have control over the URLs and you have to work with ambiguous URLs without recognizable extensions. In this situation, you can specify an explicit loader:

promise = Assets.load({
  src: 'https://example.com/ambiguous-file-name',
  loadParser: 'loadTextures'
})

Here are some of the loader values you can use:

  • Textures: loadTextures
  • Web fonts: loadWebFont
  • Json files: loadJson
  • Text files: loadTxt

Warning about solved promises

When an asset is downloaded, it is cached as a promise inside the Assets instance and if you try to download it again you will get a reference to the already resolved promise. However promise handlers .then(...)/.catch(...)/.finally(...) are always asynchronous, this means that even if a promise was already resolved the code below the .then(...)/.catch(...)/.finally(...) will execute before the code inside them. See this example:

console.log(1);
alreadyResolvedPromise.then(() => console.log(2));
console.log(3);

// Console output:
// 1
// 3
// 2

To learn more about why this happens you will need to learn about Microtasks, however, using async functions should mitigate this problem.

Using Async/Await

There is a way to work with promises that is more intuitive and easier to read: async/await.

To use it we first need to create a function/method and mark it as async.

async function test() {
    // ...
}

This function now wraps the return value in a promise and allows us to use the await keyword before a promise to halt the execution of the code until it is resolved and gives us the value.

See this example:

// 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);
const texture = await Assets.load('https://pixijs.com/assets/bunny.png');
// Create a new Sprite from the awaited loaded Texture
const bunny = Sprite.from(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);

The texture variable now is not a promise but the resolved texture that resulted after waiting for this promise to resolve.

const texture = await Assets.load('examples/assets/bunny.png');

This allows us to write more readable code without falling into callback hell and to better think when our program halts and yields.

Loading multiple assets

We can add assets to the cache and then load them all simultaneously by using Assets.add(...) and then calling Assets.load(...) with all the keys you want to have loaded. See the following example:

// Append the application canvas to the document body
document.body.appendChild(app.canvas);
// Add the assets to load
Assets.add({ alias: 'flowerTop', src: 'https://pixijs.com/assets/flowerTop.png' });
Assets.add({ alias: 'eggHead', src: 'https://pixijs.com/assets/eggHead.png' });
// Load the assets and get a resolved promise once both are loaded
const texturesPromise = Assets.load(['flowerTop', 'eggHead']); // => Promise<{flowerTop: Texture, eggHead: Texture}>
// When the promise resolves, we have the texture!
texturesPromise.then((textures) =>
{
    // Create a new Sprite from the resolved loaded Textures
    const flower = Sprite.from(textures.flowerTop);
    flower.anchor.set(0.5);
    flower.x = app.screen.width * 0.25;
    flower.y = app.screen.height / 2;
    app.stage.addChild(flower);
    const egg = Sprite.from(textures.eggHead);
    egg.anchor.set(0.5);
    egg.x = app.screen.width * 0.75;
    egg.y = app.screen.height / 2;
    app.stage.addChild(egg);
});

However, if you want to take full advantage of @pixi/Assets you should use bundles. Bundles are just a way to group assets together and can be added manually by calling Assets.addBundle(...)/Assets.loadBundle(...).

  Assets.addBundle('animals', {
    bunny: 'bunny.png',
    chicken: 'chicken.png',
    thumper: 'thumper.png',
  });

 const assets = await Assets.loadBundle('animals');

However, the best way to handle bundles is to use a manifest and call Assets.init({manifest}) with said manifest (or even better, an URL pointing to it). Splitting our assets into bundles that correspond to screens or stages of our app will come in handy for loading in the background while the user is using the app instead of locking them in a single monolithic loading screen.

{
   "bundles":[
      {
         "name":"load-screen",
         "assets":[
            {
               "alias":"background",
               "src":"sunset.png"
            },
            {
               "alias":"bar",
               "src":"load-bar.{png,webp}"
            }
         ]
      },
      {
         "name":"game-screen",
         "assets":[
            {
               "alias":"character",
               "src":"robot.png"
            },
            {
               "alias":"enemy",
               "src":"bad-guy.png"
            }
         ]
      }
   ]
}
Assets.init({manifest: "path/manifest.json"});

Beware that you can only call init once.

Remember there is no downside in repeating URLs since they will all be cached, so if you need the same asset in two bundles you can duplicate the request without any extra cost!

Background loading

The old approach to loading was to use Loader to load all your assets at the beginning of your app, but users are less patient now and want content to be instantly available so the practices are moving towards loading the bare minimum needed to show the user some content and, while they are interacting with that, we keep loading the following content in the background.

Luckily, Assets has us covered with a system that allows us to load everything in the background and in case we need some assets right now, bump them to the top of the queue so we can minimize loading times.

To achieve this, we have the methods Assets.backgroundLoad(...) and Assets.backgroundLoadBundle(...) that will passively begin to load these assets in the background. So when you finally come to loading them you will get a promise that resolves to the loaded assets immediately.

When you finally need the assets to show, you call the usual Assets.load(...) or Assets.loadBundle(...) and you will get the corresponding promise.

The best way to do this is using bundles, see the following example:

import { Application, Assets, Sprite } from 'pixi.js';

// Create a new application
const app = new Application();

async function init()
{
    // Initialize the application
    await app.init({ background: '#1099bb', resizeTo: window });

    // Append the application canvas to the document body
    document.body.appendChild(app.canvas);

    // Manifest example
    const manifestExample = {
        bundles: [
            {
                name: 'load-screen',
                assets: [
                    {
                        alias: 'flowerTop',
                        src: 'https://pixijs.com/assets/flowerTop.png',
                    },
                ],
            },
            {
                name: 'game-screen',
                assets: [
                    {
                        alias: 'eggHead',
                        src: 'https://pixijs.com/assets/eggHead.png',
                    },
                ],
            },
        ],
    };

    await Assets.init({ manifest: manifestExample });

    // Bundles can be loaded in the background too!
    Assets.backgroundLoadBundle(['load-screen', 'game-screen']);
}

init();

We create one bundle for each screen our game will have and set them all to start downloading at the beginning of our app. If the user progresses slowly enough in our app then they should never get to see a loading screen after the first one!

Text

Whether it's a high score or a diagram label, text is often the best way to convey information in your projects. Surprisingly, drawing text to the screen with WebGL is a very complex process - there's no built in support for it at all. One of the values PixiJS provides is in hiding this complexity to allow you to draw text in diverse styles, fonts and colors with a few lines of code. In addition, these bits of text are just as much scene objects as sprites - you can tint text, rotate it, alpha-blend it, and otherwise treat it like any other graphical object.

Let's dig into how this works.

There Are Three Kinds of Text

Because of the challenges of working with text in WebGL, PixiJS provides three very different solutions. In this guide, we're going to go over both methods in some detail to help you make the right choice for your project's needs. Selecting the wrong text type can have a large negative impact on your project's performance and appearance.

The Text Object

In order to draw text to the screen, you use a Text object. Under the hood, this class draws text to an off-screen buffer using the browser's normal text rendering, then uses that offscreen buffer as the source for drawing the text object. Effectively what this means is that whenever you create or change text, PixiJS creates a new rasterized image of that text, and then treats it like a sprite. This approach allows truly rich text display while keeping rendering speed high.

So when working with Text objects, there are two sets of options - standard display object options like position, rotation, etc that work after the text is rasterized internally, and text style options that are used while rasterizing. Because text once rendered is basically just a sprite, there's no need to review the standard options. Instead, let's focus on how text is styled.

Check out the text example code.

Text Styles

There are a lot of text style options available (see TextStyle), but they break down into 5 main groups:

Font: fontFamily to select the webfont to use, fontSize to specify the size of the text to draw, along with options for font weight, style and variant.

Appearance: Set the color with fill or add a stroke outline, including options for gradient fills. For more information on the fill property, see the Graphics Fill guide.

Drop-Shadows: Set a drop-shadow with dropShadow, with a host of related options to specify offset, blur, opacity, etc.

Layout: Enable with wordWrap and wordWrapWidth, and then customize the lineHeight and align or letterSpacing

Utilities: Add padding or trim extra space to deal with funky font families if needed.

To interactively test out feature of Text Style, check out this tool.

Loading and Using Fonts

In order for PixiJS to build a Text object, you'll need to make sure that the font you want to use is loaded by the browser. This can be easily accomplished with our good friends Assets

// load the fonts
await Assets.load('short-stack.woff2');

// now they can be used!

const text = new Text({
  text:'hello',
  style:{
    fontFamily:'short-stack'
  }
})

Caveats and Gotchas

While PixiJS does make working with text easy, there are a few things you need to watch out for.

First, changing an existing text string requires re-generating the internal render of that text, which is a slow operation that can impact performance if you change many text objects each frame. If your project requires lots of frequently changing text on the screen at once, consider using a BitmapText object (explained below) which uses a fixed bitmap font that doesn't require re-generation when text changes.

Second, be careful when scaling text. Setting a text object's scale to > 1.0 will result in blurry/pixely display, because the text is not re-rendered at the higher resolution needed to look sharp - it's still the same resolution it was when generated. To deal with this, you can render at a higher initial size and down-scale, instead. This will use more memory, but will allow your text to always look clear and crisp.

BitmapText

In addition to the standard Text approach to adding text to your project, PixiJS also supports bitmap fonts. Bitmap fonts are very different from TrueType or other general purpose fonts, in that they consist of a single image containing pre-rendered versions of every letter you want to use. When drawing text with a bitmap font, PixiJS doesn't need to render the font glyphs into a temporary buffer - it can simply copy and stamp out each character of a string from the master font image.

The primary advantage of this approach is speed - changing text frequently is much cheaper and rendering each additional piece of text is much faster due to the shared source texture.

Check out the bitmap text example code.

BitmapFont

  • 3rd party solutions
  • BitmapFont.from auto-generation

Selecting the Right Approach

Text

  • Static text
  • Small number of text objects
  • High fidelity text rendering (kerning e.g.)
  • Text layout (line & letter spacing)

BitmapText

  • Dynamic text
  • Large number of text objects
  • Lower memory

HTMLText

  • Static text
  • Need that HTML formatting

Graphics

Graphics is a complex and much misunderstood tool in the PixiJS toolbox. At first glance, it looks like a tool for drawing shapes. And it is! But it can also be used to generate masks. How does that work?

In this guide, we're going to de-mystify the Graphics object, starting with how to think about what it does.

Check out the graphics example code.

Graphics Is About Building - Not Drawing

First-time users of the Graphics class often struggle with how it works. Let's look at an example snippet that creates a Graphics object and draws a rectangle:

// Create a Graphics object, draw a rectangle and fill it
let obj = new Graphics()
  .rect(0, 0, 200, 100)
  .fill(0xff0000);

// Add it to the stage to render
app.stage.addChild(obj);

That code will work - you'll end up with a red rectangle on the screen. But it's pretty confusing when you start to think about it. Why am I drawing a rectangle when constructing the object? Isn't drawing something a one-time action? How does the rectangle get drawn the second frame? And it gets even weirder when you create a Graphics object with a bunch of drawThis and drawThat calls, and then you use it as a mask. What???

The problem is that the function names are centered around drawing, which is an action that puts pixels on the screen. But in spite of that, the Graphics object is really about building.

Let's look a bit deeper at that rect() call. When you call rect(), PixiJS doesn't actually draw anything. Instead, it stores the rectangle you "drew" into a list of geometry for later use. If you then add the Graphics object to the scene, the renderer will come along, and ask the Graphics object to render itself. At that point, your rectangle actually gets drawn - along with any other shapes, lines, etc. that you've added to the geometry list.

Once you understand what's going on, things start to make a lot more sense. When you use a Graphics object as a mask, for example, the masking system uses that list of graphics primitives in the geometry list to constrain which pixels make it to the screen. There's no drawing involved.

That's why it helps to think of the Graphics class not as a drawing tool, but as a geometry building tool.

Types of Primitives

There are a lot of functions in the Graphics class, but as a quick orientation, here's the list of basic primitives you can add:

  • Line
  • Rect
  • RoundRect
  • Circle
  • Ellipse
  • Arc
  • Bezier and Quadratic Curve

In addition, you have access to the following complex primitives:

  • Torus
  • Chamfer Rect
  • Fillet Rect
  • Regular Polygon
  • Star
  • Rounded Polygon

There is also support for svg. But due to the nature of how PixiJS renders holes (it favours performance) Some complex hole shapes may render incorrectly. But for the majority of shapes, this will do the trick!

 let mySvg = new Graphics().svg(`
   <svg>
     <path d="M 100 350 q 150 -300 300 0" stroke="blue" />
   </svg>
  `);

The GraphicsContext

Understanding the relationship between Sprites and their shared Texture can help grasp the concept of a GraphicsContext. Just as multiple Sprites can utilize a single Texture, saving memory by not duplicating pixel data, a GraphicsContext can be shared across multiple Graphics objects.

This sharing of a GraphicsContext means that the intensive task of converting graphics instructions into GPU-ready geometry is done once, and the results are reused, much like textures. Consider the difference in efficiency between these approaches:

Creating individual circles without sharing a context:

// Create 5 circles
for (let i = 0; i < 5; i++) {
  let circle = new Graphics()
    .circle(100, 100, 50)
    .fill('red');
}

Versus sharing a GraphicsContext:

// Create a master Graphicscontext
let circleContext = new GraphicsContext()
  .circle(100, 100, 50)
  .fill('red')

// Create 5 duplicate objects
for (let i = 0; i < 5; i++) {
  // Initialize the duplicate using our circleContext
  let duplicate = new Graphics(circleContext);
}

Now, this might not be a huge deal for circles and squares, but when you are using SVGs, it becomes quite important to not have to rebuild each time and instead share a GraphicsContext. It's recommended for maximum performance to create your contexts upfront and reuse them, just like textures!

let circleContext = new GraphicsContext()
  .circle(100, 100, 50)
  .fill('red')

let rectangleContext = new GraphicsContext()
  .rect(0, 0, 50, 50)
  .fill('red')

let frames = [circleContext, rectangleContext];
let frameIndex = 0;

const graphics = new Graphics(frames[frameIndex]);

// animate from square to circle:

function update()
{
  // swap the context - this is a very cheap operation!
  // much cheaper than clearing it each frame.
  graphics.context = frames[frameIndex++%frames.length];
}

If you don't explicitly pass a GraphicsContext when creating a Graphics object, then internally, it will have its own context, accessible via myGraphics.context. The GraphicsContext class manages the list of geometry primitives created by the Graphics parent object. Graphics functions are literally passed through to the internal contexts:

let circleGraphics = new Graphics()
  .circle(100, 100, 50)
  .fill('red')

same as:

let circleGraphics = new Graphics()

circleGraphics.context
  .circle(100, 100, 50)
  .fill('red')

Calling Graphics.destroy() will destroy the graphics. If a context was passed to it via the constructor then it will leave the destruction of that context to you. However if the context is internally created (the default), when destroyed the Graphics object will destroy its internal GraphicsContext.

Graphics For Display

OK, so now that we've covered how the Graphics class works, let's look at how you use it. The most obvious use of a Graphics object is to draw dynamically generated shapes to the screen.

Doing so is simple. Create the object, call the various builder functions to add your custom primitives, then add the object to the scene graph. Each frame, the renderer will come along, ask the Graphics object to render itself, and each primitive, with associated line and fill styles, will be drawn to the screen.

Graphics as a Mask

You can also use a Graphics object as a complex mask. To do so, build your object and primitives as usual. Next create a Container object that will contain the masked content, and set its mask property to your Graphics object. The children of the container will now be clipped to only show through inside the geometry you've created. This technique works for both WebGL and Canvas-based rendering.

Check out the masking example code.

Caveats and Gotchas

The Graphics class is a complex beast, and so there are a number of things to be aware of when using it.

Memory Leaks: Call destroy() on any Graphics object you no longer need to avoid memory leaks.

Holes: Holes you create have to be completely contained in the shape or else it may not be able to triangulate correctly.

Changing Geometry: If you want to change the shape of a Graphics object, you don't need to delete and recreate it. Instead you can use the clear() function to reset the contents of the geometry list, then add new primitives as desired. Be careful of performance when doing this every frame.

Performance: Graphics objects are generally quite performant. However, if you build highly complex geometry, you may pass the threshold that permits batching during rendering, which can negatively impact performance. It's better for batching to use many Graphics objects instead of a single Graphics with many shapes.

Transparency: Because the Graphics object renders its primitives sequentially, be careful when using blend modes or partial transparency with overlapping geometry. Blend modes like ADD and MULTIPLY will work on each primitive, not on the final composite image. Similarly, partially transparent Graphics objects will show primitives overlapping. To apply transparency or blend modes to a single flattened surface, consider using AlphaFilter or RenderTexture.

Graphics Fill

If you are new to graphics, please check out the graphics guide here. This guide dives a bit deeper into a specific aspect of graphics: how to fill them! The fill() method in PixiJS is particularly powerful, enabling you to fill shapes with colors, textures, or gradients. Whether you're designing games, UI components, or creative tools, mastering the fill() method is essential for creating visually appealing and dynamic graphics. This guide explores the different ways to use the fill() method to achieve stunning visual effects.

:::info Note The fillStyles discussed here can also be applied to Text objects! :::

Basic Color Fills

When creating a Graphics object, you can easily fill it with a color using the fill() method. Here's a simple example:

const obj = new Graphics()
  .rect(0, 0, 200, 100) // Create a rectangle with dimensions 200x100
  .fill('red'); // Fill the rectangle with a red color

alt text

This creates a red rectangle. PixiJS supports multiple color formats for the fill() method. Developers can choose a format based on their needs. For example, CSS color strings are user-friendly and readable, hexadecimal strings are compact and widely used in design tools, and numbers are efficient for programmatic use. Arrays and Color objects offer precise control, making them ideal for advanced graphics.

  • CSS color strings (e.g., 'red', 'blue')
  • Hexadecimal strings (e.g., '#ff0000')
  • Numbers (e.g., 0xff0000)
  • Arrays (e.g., [255, 0, 0])
  • Color objects for precise color control

Examples:

// Using a number
const obj1 = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);

// Using a hex string
const obj2 = new Graphics().rect(0, 0, 100, 100).fill('#ff0000');

// Using an array
const obj3 = new Graphics().rect(0, 0, 100, 100).fill([255, 0, 0]);

// Using a Color object
const color = new Color();
const obj4 = new Graphics().rect(0, 0, 100, 100).fill(color);

Fill with a Style Object

For more advanced fills, you can use a FillStyle object. This allows for additional customization, such as setting opacity:

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill({
    color: 'red',
    alpha: 0.5, // 50% opacity
  });

alt text

Fill with Textures

Filling shapes with textures is just as simple:

const texture = await Assets.load('assets/image.png');
const obj = new Graphics().rect(0, 0, 100, 100)
  .fill(texture);

alt text

Local vs. Global Texture Space

Textures can be applied in two coordinate spaces:

  • Local Space (Default): The texture coordinates are mapped relative to the shape's dimensions and position. The texture coordinates use a normalized coordinate system where (0,0) is the top-left and (1,1) is the bottom-right of the shape, regardless of its actual pixel dimensions. For example, if you have a 300x200 pixel texture filling a 100x100 shape, the texture will be scaled to fit exactly within those 100x100 pixels. The texture's top-left corner (0,0) will align with the shape's top-left corner, and the texture's bottom-right corner (1,1) will align with the shape's bottom-right corner, stretching or compressing the texture as needed.
const shapes = new PIXI.Graphics()
    .rect(50,50,100, 100)
    .circle(250,100,50)
    .star(400,100,6,60,40)
    .roundRect(500,50,100,100,10)
    .fill({
        texture,
        textureSpace:'local' // default!
    });

alt text

  • Global Space: Set textureSpace: 'global' to make the texture position and scale relative to the Graphics object's coordinate system. Despite the name, this isn't truly "global" - the texture remains fixed relative to the Graphics object itself, maintaining its position even when the object moves or scales. See how the image goes across all the shapes (in the same graphics) below:
const shapes = new PIXI.Graphics()
    .rect(50,50,100, 100)
    .circle(250,100,50)
    .star(400,100,6,60,40)
    .roundRect(500,50,100,100,10)
    .fill({
        texture,
        textureSpace:'global'
    });

alt text

Using Matrices with Textures

To modify texture coordinates, you can apply a transformation matrix, which is a mathematical tool used to scale, rotate, or translate the texture. If you're unfamiliar with transformation matrices, they allow for precise control over how textures are rendered, and you can explore more about them here.

const matrix = new Matrix().scale(0.5, 0.5);

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill({
    texture: texture,
    matrix: matrix, // scale the texture down by 2
  });

alt text

Texture Gotcha's

  1. Sprite Sheets: If using a texture from a sprite sheet, the entire source texture will be used. To use a specific frame, create a new texture:
const spriteSheetTexture = Texture.from('assets/my-sprite-sheet.png');
const newTexture = renderer.generateTexture(Sprite.from(spriteSheetTexture));

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill(newTexture);
  1. Power of Two Textures: Textures should be power-of-two dimensions for proper tiling in WebGL1 (WebGL2 and WebGPU are fine).

Fill with Gradients

PixiJS supports both linear and radial gradients, which can be created using the FillGradient class. Gradients are particularly useful for adding visual depth and dynamic styling to shapes and text.

Linear Gradients

Linear gradients create a smooth color transition along a straight line. Here is an example of a simple linear gradient:

const gradient = new FillGradient({
  type: 'linear',
  colorStops: [
    { offset: 0, color: 'yellow' },
    { offset: 1, color: 'green' },
  ],
});

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill(gradient);

alt text

You can control the gradient direction with the following properties:

  • start {x, y}: These define the starting point of the gradient. For example, in a linear gradient, this is where the first color stop is positioned. These values are typically expressed in relative coordinates (0 to 1), where 0 represents the left/top edge and 1 represents the right/bottom edge of the shape.

  • end {x, y}: These define the ending point of the gradient. Similar to start {x, y}, these values specify where the last color stop is positioned in the shape's local coordinate system.

Using these properties, you can create various gradient effects, such as horizontal, vertical, or diagonal transitions. For example, setting start to {x: 0, y: 0} and end to {x: 1, y: 1} would result in a diagonal gradient from the top-left to the bottom-right of the shape.

const diagonalGradient = new FillGradient({
  type: 'linear',
  start: { x: 0, y: 0 },
  end: { x: 1, y: 1 },
  colorStops: [
    { offset: 0, color: 'yellow' },
    { offset: 1, color: 'green' },
  ],
});

alt text

Radial Gradients

Radial gradients create a smooth color transition in a circular pattern. Unlike linear gradients, they blend colors from one circle to another. Here is an example of a simple radial gradient:

const gradient = new FillGradient({
  type: 'radial',
  colorStops: [
    { offset: 0, color: 'yellow' },
    { offset: 1, color: 'green' },
  ],
});

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill(gradient);

alt text

You can control the gradient's shape and size using the following properties:

  • center {x, y}: These define the center of the inner circle where the gradient starts. Typically, these values are expressed in relative coordinates (0 to 1), where 0.5 represents the center of the shape.

  • innerRadius: The radius of the inner circle. This determines the size of the gradient's starting point.

  • outerCenter {x, y}: These define the center of the outer circle where the gradient ends. Like center {x, y}, these values are also relative coordinates.

  • outerRadius: The radius of the outer circle. This determines the size of the gradient's ending point.

By adjusting these properties, you can create a variety of effects, such as small, concentrated gradients or large, expansive ones. For example, setting a small r0 and a larger r1 will create a gradient that starts does not start to transition until the inner circle radius is reached.

const radialGradient = new FillGradient({
  type: 'radial',
  center: { x: 0.5, y: 0.5 },
  innerRadius: 0.25,
  outerCenter: { x: 0.5, y: 0.5 },
  outerRadius: 0.5,
  colorStops: [
    { offset: 0, color: 'blue' },
    { offset: 1, color: 'red' },
  ],
});

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill(gradient);

alt text

Gradient Gotcha's

  1. Memory Management: Use fillGradient.destroy() to free up resources when gradients are no longer needed.

  2. Animation: Update existing gradients instead of creating new ones for better performance.

  3. Custom Shaders: For complex animations, custom shaders may be more efficient.

  4. Texture and Matrix Limitations: Under the hood, gradient fills set both the texture and matrix properties internally. This means you cannot use a texture fill or matrix transformation at the same time as a gradient fill.

Combining Textures and Colors

You can combine a texture or gradients with a color tint and alpha to achieve more complex and visually appealing effects. This allows you to overlay a color on top of the texture or gradient, adjusting its transparency with the alpha value.

const gradient = new FillGradient({
    colorStops: [
        { offset: 0, color: 'blue' },
        { offset: 1, color: 'red' },
    ]
});

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill({
    fill: gradient,
    color: 'yellow',
    alpha: 0.5,
  });

alt text

const obj = new Graphics().rect(0, 0, 100, 100)
  .fill({
    texture: texture,
    color: 'yellow',
    alpha: 0.5,
  });

alt text


Hopefully, this guide has shown you how easy and powerful fills can be when working with graphics (and text!). By mastering the fill() method, you can unlock endless possibilities for creating visually dynamic and engaging graphics in PixiJS. Have fun!

Interaction

PixiJS is primarily a rendering system, but it also includes support for interactivity. Adding support for mouse and touch events to your project is simple and consistent.

Event Modes

Prior to v7, interaction was defined and managed by the Interaction package and its InteractionManager. Beginning with v7, however, a new event-based system has replaced the previous Interaction package, and expanded the definition of what it means for a Container to be interactive.

With this, we have introduced eventMode which allows you to control how an object responds to interaction events. If you're familiar with the former Interaction system, the eventMode is similar to the interactive property, but with more options.

eventMode Description
none Ignores all interaction events, similar to CSS's pointer-events: none. Good optimization for non-interactive children.
passive The default eventMode for all containers. Does not emit events and ignores hit-testing on itself, but does allow for events and hit-testing on its interactive children.
auto Does not emit events, but is hit tested if parent is interactive. Same as interactive = false in v7.
static Emits events and is hit tested. Same as interaction = true in v7. Useful for objects like buttons that do not move.
dynamic Emits events and is hit tested, but will also receive mock interaction events fired from a ticker to allow for interaction when the mouse isn't moving. Useful for elements that are independently moving or animating.

Event Types

PixiJS supports the following event types:

Event Type Description
pointercancel Fired when a pointer device button is released outside the display object that initially registered a pointerdown.
pointerdown Fired when a pointer device button is pressed on the display object.
pointerenter Fired when a pointer device enters the display object.
pointerleave Fired when a pointer device leaves the display object.
pointermove Fired when a pointer device is moved while over the display object.
globalpointermove Fired when a pointer device is moved, regardless of hit-testing the current object.
pointerout Fired when a pointer device is moved off the display object.
pointerover Fired when a pointer device is moved onto the display object.
pointertap Fired when a pointer device is tapped on the display object.
pointerup Fired when a pointer device button is released over the display object.
pointerupoutside Fired when a pointer device button is released outside the display object that initially registered a pointerdown.
mousedown Fired when a mouse button is pressed on the display object.
mouseenter Fired when the mouse cursor enters the display object.
mouseleave Fired when the mouse cursor leaves the display object.
mousemove Fired when the mouse cursor is moved while over the display object.
globalmousemove Fired when a mouse is moved, regardless of hit-testing the current object.
mouseout Fired when the mouse cursor is moved off the display object.
mouseover Fired when the mouse cursor is moved onto the display object.
mouseup Fired when a mouse button is released over the display object.
mouseupoutside Fired when a mouse button is released outside the display object that initially registered a mousedown.
click Fired when a mouse button is clicked (pressed and released) over the display object.
touchcancel Fired when a touch point is removed outside of the display object that initially registered a touchstart.
touchend Fired when a touch point is removed from the display object.
touchendoutside Fired when a touch point is removed outside of the display object that initially registered a touchstart.
touchmove Fired when a touch point is moved along the display object.
globaltouchmove Fired when a touch point is moved, regardless of hit-testing the current object.
touchstart Fired when a touch point is placed on the display object.
tap Fired when a touch point is tapped on the display object.
wheel Fired when a mouse wheel is spun over the display object.
rightclick Fired when a right mouse button is clicked (pressed and released) over the display object.
rightdown Fired when a right mouse button is pressed on the display object.
rightup Fired when a right mouse button is released over the display object.
rightupoutside Fired when a right mouse button is released outside the display object that initially registered a rightdown.

Enabling Interaction

Any Container-derived object (Sprite, Container, etc.) can become interactive simply by setting its eventMode property to any of the eventModes listed above. Doing so will cause the object to emit interaction events that can be responded to in order to drive your project's behavior.

Check out the click interactivity example code.

To respond to clicks and taps, bind to the events fired on the object, like so:

let sprite = Sprite.from('/some/texture.png');
sprite.on('pointerdown', (event) => { alert('clicked!'); });
sprite.eventMode = 'static';

Check out the Container for the list of interaction events supported.

Checking if an Object is Interactive

You can check if an object is interactive by calling the isInteractive property. This will return true if eventMode is set to static or dynamic.

if (sprite.isInteractive()) {
    // sprite is interactive
}

Use Pointer Events

PixiJS supports three types of interaction events: mouse, touch, and pointer.

  • Mouse events are fired by mouse movement, clicks etc.
  • Touch events are fired for touch-capable devices. And,
  • Pointer events are fired for both.

What this means is that, in many cases, you can write your project to use pointer events and it will just work when used with either mouse or touch input.

Given that, the only reason to use non-pointer events is to support different modes of operation based on input type or to support multi-touch interaction. In all other cases, prefer pointer events.

Optimization

Hit testing requires walking the full object tree, which in complex projects can become an optimization bottleneck.

To mitigate this issue, PixiJS Container-derived objects have a property named interactiveChildren. If you have Containers or other objects with complex child trees that you know will never be interactive, you can set this property to false, and the hit-testing algorithm will skip those children when checking for hover and click events.

As an example, if you were building a side-scrolling game, you would probably want to set background.interactiveChildren = false for your background layer with rocks, clouds, flowers, etc. Doing so would substantially speed up hit-testing due to the number of unclickable child objects the background layer would contain.

The EventSystem can also be customised to be more performant:

const app = new Application({
    eventMode: 'passive',
    eventFeatures: {
        move: true,
        /** disables the global move events which can be very expensive in large scenes */
        globalMove: false,
        click: true,
        wheel: true,
    }
});

Advanced Usage & Performance

Cache As Texture

Using cacheAsTexture in PixiJS

The cacheAsTexture function in PixiJS is a powerful tool for optimizing rendering in your applications. By rendering a container and its children to a texture, cacheAsTexture can significantly improve performance for static or infrequently updated containers. Let's explore how to use it effectively, along with its benefits and considerations.

:::info[Note] cacheAsTexture is PixiJS v8's equivalent of the previous cacheAsBitmap functionality. If you're migrating from v7 or earlier, simply replace cacheAsBitmap with cacheAsTexture in your code. :::


What Is cacheAsTexture?

When you set container.cacheAsTexture(), the container is rendered to a texture. Subsequent renders reuse this texture instead of rendering all the individual children of the container. This approach is particularly useful for containers with many static elements, as it reduces the rendering workload.

To update the texture after making changes to the container, call:

container.updateCacheTexture();

and to turn it off, call:

container.cacheAsTexture(false);

Basic Usage

Here's an example that demonstrates how to use cacheAsTexture:

import * as PIXI 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 sprite sheet..
    await Assets.load('https://pixijs.com/assets/spritesheet/monsters.json');

    // holder to store aliens
    const aliens = [];
    const alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png'];

    let count = 0;

    // create an empty container
    const alienContainer = new Container();

    alienContainer.x = 400;
    alienContainer.y = 300;

    app.stage.addChild(alienContainer);

    // add a bunch of aliens with textures from image paths
    for (let i = 0; i < 100; i++)
    {
        const frameName = alienFrames[i % 4];

        // create an alien using the frame name..
        const alien = Sprite.from(frameName);

        alien.tint = Math.random() * 0xffffff;

        alien.x = Math.random() * 800 - 400;
        alien.y = Math.random() * 600 - 300;
        alien.anchor.x = 0.5;
        alien.anchor.y = 0.5;
        aliens.push(alien);
        alienContainer.addChild(alien);
    }

    // this will cache the container and its children as a single texture
    // so instead of drawing 100 sprites, it will draw a single texture!
    alienContainer.cacheAsTexture()
})();

In this example, the container and its children are rendered to a single texture, reducing the rendering overhead when the scene is drawn.

Play around with the example here.

Advanced Usage

Instead of enabling cacheAsTexture with true, you can pass a configuration object which is very similar to texture source options.

container.cacheAsTexture({
    resolution: 2,
    antialias: true,
});
  • resolution is the resolution of the texture. By default this is the same as you renderer or application.
  • antialias is the antialias mode to use for the texture. Much like the resolution this defaults to the renderer or application antialias mode.

Benefits of cacheAsTexture

  • Performance Boost: Rendering a complex container as a single texture avoids the need to process each child element individually during each frame.
  • Optimized for Static Content: Ideal for containers with static or rarely updated children.

Advanced Details

  • Memory Tradeoff: Each cached texture requires GPU memory. Using cacheAsTexture trades rendering speed for increased memory usage.
  • GPU Limitations: If your container is too large (e.g., over 4096x4096 pixels), the texture may fail to cache, depending on GPU limitations.

How It Works Internally

Under the hood, cacheAsTexture converts the container into a render group and renders it to a texture. It uses the same texture cache mechanism as filters:

container.enableRenderGroup();
container.renderGroup.cacheAsTexture = true;

Once the texture is cached, updating it via updateCacheTexture() is efficient and incurs minimal overhead. Its as fast as rendering the container normally.


Best Practices

DO:
  • Use for Static Content: Apply cacheAsTexture to containers with elements that don't change frequently, such as a UI panel with static decorations.
  • Leverage for Performance: Use cacheAsTexture to render complex containers as a single texture, reducing the overhead of processing each child element individually every frame. This is especially useful for containers that contain expensive effects eg filters.
  • Switch of Antialiasing: setting antialiasing to false can give a small performance boost, but the texture may look a bit more pixelated around its children's edges.
  • Resolution: Do adjust the resolution based on your situation, if something is scaled down, you can use a lower resolution.If something is scaled up, you may want to use a higher resolution. But be aware that the higher the resolution the larger the texture and memory footprint.
DON'T:
  • Apply to Very Large Containers: Avoid using cacheAsTexture on containers that are too large (e.g., over 4096x4096 pixels), as they may fail to cache due to GPU limitations. Instead, split them into smaller containers.
  • Overuse for Dynamic Content: Flick cacheAsTexture on / off frequently on containers, as this results in constant re-caching, negating its benefits. Its better to Cache as texture when you once, and then use updateCacheTexture to update it.
  • Apply to Sparse Content: Do not use cacheAsTexture for containers with very few elements or sparse content, as the performance improvement will be negligible.
  • Ignore Memory Impact: Be cautious of GPU memory usage. Each cached texture consumes memory, so overusing cacheAsTexture can lead to resource constraints.

Gotchas

  • Rendering Depends on Scene Visibility: The cache updates only when the containing scene is rendered. Modifying the layout after setting cacheAsTexture but before rendering your scene will be reflected in the cache.

  • Containers are rendered with no transform: Cached items are rendered at their actual size, ignoring transforms like scaling. For instance, an item scaled down by 50%, its texture will be cached at 100% size and then scaled down by the scene.

  • Caching and Filters: Filters may not behave as expected with cacheAsTexture. To cache the filter effect, wrap the item in a parent container and apply cacheAsTexture to the parent.

  • Reusing the texture: If you want to create a new texture based on the container, its better to use const texture = renderer.generateTexture(container) and share that amongst you objects!

By understanding and applying cacheAsTexture strategically, you can significantly enhance the rendering performance of your PixiJS projects. Happy coding!

Render Groups

Understanding RenderGroups in PixiJS

As you delve deeper into PixiJS, especially with version 8, you'll encounter a powerful feature known as RenderGroups. Think of RenderGroups as specialized containers within your scene graph that act like mini scene graphs themselves. Here's what you need to know to effectively use Render Groups in your projects:

What Are Render Groups?

Render Groups are essentially containers that PixiJS treats as self-contained scene graphs. When you assign parts of your scene to a Render Group, you're telling PixiJS to manage these objects together as a unit. This management includes monitoring for changes and preparing a set of render instructions specifically for the group. This is a powerful tool for optimizing your rendering process.

Why Use Render Groups?

The main advantage of using Render Groups lies in their optimization capabilities. They allow for certain calculations, like transformations (position, scale, rotation), tint, and alpha adjustments, to be offloaded to the GPU. This means that operations like moving or adjusting the Render Group can be done with minimal CPU impact, making your application more performance-efficient.

In practice, you're utilizing Render Groups even without explicit awareness. The root element you pass to the render function in PixiJS is automatically converted into a RenderGroup as this is where its render instructions will be stored. Though you also have the option to explicitly create additional RenderGroups as needed to further optimize your project.

This feature is particularly beneficial for:

  • Static Content: For content that doesn't change often, a Render Group can significantly reduce the computational load on the CPU. In this case static refers to the scene graph structure, not that actual values of the PixiJS elements inside it (eg position, scale of things).
  • Distinct Scene Parts: You can separate your scene into logical parts, such as the game world and the HUD (Heads-Up Display). Each part can be optimized individually, leading to overall better performance.

Examples

const myGameWorld = new Container({
  isRenderGroup:true
})

const myHud = new Container({
  isRenderGroup:true
})

scene.addChild(myGameWorld, myHud)

renderer.render(scene) // this action will actually convert the scene to a render group under the hood

Check out the container example.

Best Practices

  • Don't Overuse: While Render Groups are powerful, using too many can actually degrade performance. The goal is to find a balance that optimizes rendering without overwhelming the system with too many separate groups. Make sure to profile when using them. The majority of the time you won't need to use them at all!
  • Strategic Grouping: Consider what parts of your scene change together and which parts remain static. Grouping dynamic elements separately from static elements can lead to performance gains.

Performance Tips

General

  • Only optimize when you need to! PixiJS can handle a fair amount of content off the bat
  • Be mindful of the complexity of your scene. The more objects you add the slower things will end up
  • Order can help, for example sprite / graphic / sprite / graphic is slower than sprite / sprite / graphic / graphic
  • Some older mobile devices run things a little slower. Passing in the option useContextAlpha: false and antialias: false to the Renderer or Application can help with performance
  • Culling is disabled by default as it's often better to do this at an application level or set objects to be cullable = true. If you are GPU-bound it will improve performance; if you are CPU-bound it will degrade performance

Sprites

  • Use Spritesheets where possible to minimize total textures
  • Sprites can be batched with up to 16 different textures (dependent on hardware)
  • This is the fastest way to render content
  • On older devices use smaller low resolution textures
  • Add the extention @0.5x.png to the 50% scale-down spritesheet so PixiJS will visually-double them automatically
  • Draw order can be important

Graphics

  • Graphics objects are fastest when they are not modified constantly (not including the transform, alpha or tint!)
  • Graphics objects are batched when under a certain size (100 points or smaller)
  • Small Graphics objects are as fast as Sprites (rectangles, triangles)
  • Using 100s of graphics complex objects can be slow, in this instance use sprites (you can create a texture)

Texture

  • Textures are automatically managed by a Texture Garbage Collector
  • You can also manage them yourself by using texture.destroy()
  • If you plan to destroy more than one at once add a random delay to their destruction to remove freezing
  • Delay texture destroy if you plan to delete a lot of textures yourself

Text

  • Avoid changing it on every frame as this can be expensive (each time it draws to a canvas and then uploads to GPU)
  • Bitmap Text gives much better performance for dynamically changing text
  • Text resolution matches the renderer resolution, decrease resolution yourself by setting the resolution property, which can consume less memory

Masks

  • Masks can be expensive if too many are used: e.g., 100s of masks will really slow things down
  • Axis-aligned Rectangle masks are the fastest (as they use scissor rect)
  • Graphics masks are second fastest (as they use the stencil buffer)
  • Sprite masks are the third fastest (they use filters). They are really expensive. Do not use too many in your scene!

Filters

  • Release memory: container.filters = null
  • If you know the size of them: container.filterArea = new Rectangle(x,y,w,h). This can speed things up as it means the object does not need to be measured
  • Filters are expensive, using too many will start to slow things down!

BlendModes

  • Different blend modes will cause batches to break (de-optimize)
  • ScreenSprite / NormalSprite / ScreenSprite / NormalSprite would be 4 draw calls
  • ScreenSprite / ScreenSprite / NormalSprite / NormalSprite would be 2 draw calls

Events

  • If an object has no interactive children use interactiveChildren = false. The event system will then be able to avoid crawling through the object
  • Setting hitArea = new Rectangle(x,y,w,h) as above should stop the event system from crawling through the object

Tutorials

Getting Started Example

import { Application } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
})();

Getting Started

Welcome to the PixiJS tutorial!

Please go through the tutorial steps at your own pace and challenge yourself using the editor on the right hand side. Here PixiJS has already been included as guided under the Getting Started section. Let's start with the creation of a PixiJS canvas application and add its view to the DOM.

We will be using an asynchronous immediately invoked function expression (IIFE), but you are free to switch to use promises instead.

Application Setup

Let's create the application and initialize it within the IIFE before appending its canvas to the DOM. If you came from PixiJS v7 or below, the key differences to pay attention to is that application options are now passed in as an object parameter to the init call, and that it is asynchronous which should be awaited before proceeding to use the application.

const app = new Application();

await app.init({ background: '#1099bb', resizeTo: window });
document.body.appendChild(app.canvas);

When you are ready, proceed to the next exercise using the Next > button below, or feel free to skip to any exercise using the drop-down menu on the top right hand corner of the card.

import { Application } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
})();
import { Application, Assets, Sprite } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the bunny texture.
    const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

    // Create a new Sprite from an image path
    const bunny = new Sprite(texture);

    // Add to stage
    app.stage.addChild(bunny);

    // 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;
})();

Creating a Sprite

So far all we've been doing is prep work. We haven't actually told PixiJS to draw anything. Let's fix that by adding an image to be displayed.

There are a number of ways to draw images in PixiJS, but the simplest is by using a Sprite. We'll get into the details of how the scene graph works in a later guide, but for now all you need to know is that PixiJS renders a hierarchy of Containers. A Sprite is an extension of Container that wraps a loaded image resource to allow drawing it, scaling it, rotating it, and so forth.

Before PixiJS can render an image, it needs to be loaded. Just like in any web page, image loading happens asynchronously. For now, we will simply load a single texture up on the spot with the Assets utility class.

const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

Then we need to create and add our new bunny sprite to the stage. The stage is also simply a Container that is the root of the scene graph. Every child of the stage container will be rendered every frame. By adding our sprite to the stage, we tell PixiJS's renderer we want to draw it.

const bunny = new Sprite(texture);

app.stage.addChild(bunny);

Now let's set the Sprite's anchor and position it so that it's bang on at the center.

bunny.anchor.set(0.5);

bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
import { Application, Assets, Sprite } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the bunny texture.
    const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

    // Create a new Sprite from an image path.
    const bunny = new Sprite(texture);

    // Add to stage.
    app.stage.addChild(bunny);

    // 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;
})();
import { Application, Assets, Sprite } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the bunny texture.
    const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

    // Create a new Sprite from an image path.
    const bunny = new Sprite(texture);

    // Add to stage.
    app.stage.addChild(bunny);

    // 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;

    // Add an animation loop callback to the application's ticker.
    app.ticker.add((time) =>
    {
        /**
         * Just for fun, let's rotate mr rabbit a little.
         * Time is a Ticker object which holds time related data.
         * Here we use deltaTime, which is the time elapsed between the frame callbacks
         * to create frame-independent transformation. Keeping the speed consistent.
         */
        bunny.rotation += 0.1 * time.deltaTime;
    });
})();

Writing an Update Loop

While you can use PixiJS for static content, for most projects you'll want to add animation. Our sample app is actually cranking away, rendering the same sprite in the same place multiple times a second. All we have to do to make the image move is to update its attributes once per frame. To do this, we want to hook into the application's ticker. A ticker is a PixiJS object that runs one or more callbacks each frame. Doing so is surprisingly easy. Add the following to the end of your script block:

app.ticker.add((time) => {
    bunny.rotation += 0.1 * time.deltaTime;
});

All you need to do is to call app.ticker.add(...), pass it a callback function, and then update your scene in that function. It will get called every frame, and you can move, rotate etc. whatever you'd like to drive your project's animations.

import { Application, Assets, Sprite } from 'pixi.js';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the bunny texture.
    const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

    // Create a new Sprite from an image path.
    const bunny = new Sprite(texture);

    // Add to stage.
    app.stage.addChild(bunny);

    // 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;

    // Add an animation loop callback to the application's ticker.
    app.ticker.add((time) =>
    {
        /**
         * Just for fun, let's rotate mr rabbit a little.
         * Time is a Ticker object which holds time related data.
         * Here we use deltaTime, which is the time elapsed between the frame callbacks
         * to create frame-independent transformation. Keeping the speed consistent.
         */
        bunny.rotation += 0.1 * time.deltaTime;
    });
})();

You did it!

Congratulations! Now you are ready for the real world ~

Choo Choo Train Example

import { Application } from 'pixi.js';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
})();

Onboard the Choo Choo Train!

Welcome to the Choo Choo Train workshop!

We are going to handcraft a cute little scene of a train moving through a landscape at night. We will solely be using the Graphics API to draw out the whole scene. In this tutorial, we will be exploring a handful of methods it provides to draw a variety of shapes. For the full list of methods, please check out the Graphics documentation.

Please go through the tutorial steps at your own pace and challenge yourself using the editor on the right hand side. Here PixiJS has already been included as guided under the Getting Started section. Let's start off by creation a PixiJS application, initialize it, add its canvas to the DOM, and preload the required assets ahead of the subsequent steps.

We will be using an asynchronous immediately invoked function expression (IIFE), but you are free to switch to use promises instead.

Application Setup

Let's create the application outside of the IIFE just so that it can be referenced across other functions declared outside. We can then initialize the application and appending its canvas to the DOM inside the IIFE.

await app.init({ background: '#021f4b', resizeTo: window });
document.body.appendChild(app.canvas);

At this point, you should see the preview filled with an empty light blue background.

When you are ready, proceed to the next exercise using the Next > button below, or feel free to skip to any exercise using the drop-down menu on the top right hand corner of the card.

import { Graphics } from 'pixi.js';

export function addStars(app)
{
    const starCount = 20;

    // Create a graphics object to hold all the stars.
    const graphics = new Graphics();

    for (let index = 0; index < starCount; index++)
    {
        // Randomize the position, radius, and rotation of each star.
        const x = (index * 0.78695 * app.screen.width) % app.screen.width;
        const y = (index * 0.9382 * app.screen.height) % app.screen.height;
        const radius = 2 + Math.random() * 3;
        const rotation = Math.random() * Math.PI * 2;

        // Draw the star onto the graphics object.
        graphics.star(x, y, 5, radius, 0, rotation).fill({ color: 0xffdf00, alpha: radius / 5 });
    }

    // Add the stars to the stage.
    app.stage.addChild(graphics);
}
import { Graphics } from 'pixi.js';

export function addStars(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application } from 'pixi.js';
import { addStars } from './addStars';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
})();

Adding Stars

Let's start with the sky! It's a little plain and boring right now, so how about adding some stars to it?

Because we will be drawing many different elements on the remaining steps, let's separate the building of each element into its own function to be called from within the main IIFE. Here, the addStars function has been set up for you to fill out.

Graphics API has a built-in star(x, y, points, radius, innerRadius?, rotation?) method for this with the ability to specify number of star points, its rotation, radius and even inner radius if you prefer it with a hollow.

Here, we will use a for-loop to create a number of 5-point stars with randomized radius, rotation and deterministically randomized positions across the whole scene. Let create 20 scattered stars with a radius size between 2 - 5 units to start under a single Graphics instance. After drawing out the individual invisible shape, we can then use the fill(style) method to color it in, specifying the color and the opacity calculated from the percentage of random radius to the max radius.

TIPS: The Graphics API methods (with a few exceptions) return back the Graphics instance so it can be used for chained as you will see in the future steps

const starCount = 20;
const graphics = new Graphics();

for (let index = 0; index < starCount; index++)
{
    const x = (index * 0.78695 * app.screen.width) % app.screen.width;
    const y = (index * 0.9382 * app.screen.height) % app.screen.height;
    const radius = 2 + Math.random() * 3;
    const rotation = Math.random() * Math.PI * 2;

    graphics.star(x, y, 5, radius, 0, rotation).fill({ color: 0xffdf00, alpha: radius / 5 });
}

app.stage.addChild(graphics);
import { Graphics } from 'pixi.js';
import moonSvg from './moon.svg';

export function addMoon(app)
{
    // Create a moon graphics object from an SVG code.
    const graphics = new Graphics().svg(moonSvg);

    // Position the moon.
    graphics.x = app.screen.width / 2 + 100;
    graphics.y = app.screen.height / 8;

    // Add the moon to the stage.
    app.stage.addChild(graphics);
}
import { Graphics } from 'pixi.js';

export function addMoon(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application } from 'pixi.js';
import { addMoon } from './addMoon';
import { addStars } from './addStars';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
})();

Adding Moon

For the moon crescent, we will cheat a little bit with the included moon SVG file.

Graphics API also has a built-in svg(svgString) method for drawing vector graphics using SVG data. Have a go at it on the set up addMoon function.

const graphics = new Graphics().svg(parsedSvg);

graphics.x = app.screen.width / 2 + 100;
graphics.y = app.screen.height / 8;
app.stage.addChild(graphics);
import { Graphics } from 'pixi.js';

export function addMountains(app)
{
    // Create two mountain groups where one will be on the screen and the other will be off screen.
    // When the first group moves off screen, it will be moved to the right of the second group.
    const group1 = createMountainGroup(app);
    const group2 = createMountainGroup(app);

    // Position the 2nd group off the screen to the right.
    group2.x = app.screen.width;

    // Add the mountain groups to the stage.
    app.stage.addChild(group1, group2);

    // Animate the mountain groups
    app.ticker.add((time) =>
    {
        // Calculate the amount of distance to move the mountain groups per tick.
        const dx = time.deltaTime * 0.5;

        // Move the mountain groups leftwards.
        group1.x -= dx;
        group2.x -= dx;

        // Reposition the mountain groups when they move off screen.
        if (group1.x <= -app.screen.width)
        {
            group1.x += app.screen.width * 2;
        }
        if (group2.x <= -app.screen.width)
        {
            group2.x += app.screen.width * 2;
        }
    });
}

function createMountainGroup(app)
{
    // Create a graphics object to hold all the mountains in a group.
    const graphics = new Graphics();

    // Width of all the mountains.
    const width = app.screen.width / 2;

    // Starting point on the y-axis of all the mountains.
    // This is the bottom of the screen.
    const startY = app.screen.height;

    // Start point on the x-axis of the individual mountain.
    const startXLeft = 0;
    const startXMiddle = Number(app.screen.width) / 4;
    const startXRight = app.screen.width / 2;

    // Height of the individual mountain.
    const heightLeft = app.screen.height / 2;
    const heightMiddle = (app.screen.height * 4) / 5;
    const heightRight = (app.screen.height * 2) / 3;

    // Color of the individual mountain.
    const colorLeft = 0xc1c0c2;
    const colorMiddle = 0x7e818f;
    const colorRight = 0x8c919f;

    graphics
        // Draw the middle mountain
        .moveTo(startXMiddle, startY)
        .bezierCurveTo(
            startXMiddle + width / 2,
            startY - heightMiddle,
            startXMiddle + width / 2,
            startY - heightMiddle,
            startXMiddle + width,
            startY,
        )
        .fill({ color: colorMiddle })

        // Draw the left mountain
        .moveTo(startXLeft, startY)
        .bezierCurveTo(
            startXLeft + width / 2,
            startY - heightLeft,
            startXLeft + width / 2,
            startY - heightLeft,
            startXLeft + width,
            startY,
        )
        .fill({ color: colorLeft })

        // Draw the right mountain
        .moveTo(startXRight, startY)
        .bezierCurveTo(
            startXRight + width / 2,
            startY - heightRight,
            startXRight + width / 2,
            startY - heightRight,
            startXRight + width,
            startY,
        )
        .fill({ color: colorRight });

    return graphics;
}
import { Graphics } from 'pixi.js';

export function addMountains(app)
{
    /** -- INSERT CODE HERE -- */
}

function createMountainGroup(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application } from 'pixi.js';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addStars } from './addStars';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
})();

Adding Mountains

For the background let's put up some mountains, shall we? We will also animate them to the left to give an impression that the scene is moving rightwards.

Create Mountain Groups

Since we are moving the mountains to the left, they will eventually go off the screen and at the same time leaving empty spaces to the right. To fix this, we will be looping them back to the right of the scene once they go out of the scene view. In order to make the loop seamless, we will be making 2 mountain groups where each covers the whole scene. Then we will offset one group off the screen to the right. This is so that the second group and slowly filling in the screen from the right as the first group moving off the screen to the left before looping back to be offscreen to the right of the second group and repeating the process.

Let start by filling in the logic for creating a mountain group in the createMountainGroup() function which will return a Graphics instance of a mountain group. We will use this to create the 2 group instances later.

Here, we are using a single Graphics instance for a group of mountains. Taking into account the screen dimension we can draw out 3 mountains with different heights and colors. In this case, we will imagine the Graphics instance as a pen and for each of the mountain we move the pen to the starting position using Graphics API's moveTo(x, y) method and then contour out the mountain arc using bezierCurveTo(cx1, cy1, cx2, cy2, x, y) method, where [cx, cy] positions are control point coordinates for the curve going from where it was to the [x, y] position. Again, we then need to fill the resulted shape with fill(style).

TIPS: In this case, we do not have to connect the end point to the starting point as the Graphics' context will automatically infer a closed shape by doing so for the fill.

const graphics = new Graphics();
const width = app.screen.width / 2;
const startY = app.screen.height;
const startXLeft = 0;
const startXMiddle = Number(app.screen.width) / 4;
const startXRight = app.screen.width / 2;
const heightLeft = app.screen.height / 2;
const heightMiddle = (app.screen.height * 4) / 5;
const heightRight = (app.screen.height * 2) / 3;
const colorLeft = 0xc1c0c2;
const colorMiddle = 0x7e818f;
const colorRight = 0x8c919f;

graphics
    // Draw the middle mountain
    .moveTo(startXMiddle, startY)
    .bezierCurveTo(
        startXMiddle + width / 2,
        startY - heightMiddle,
        startXMiddle + width / 2,
        startY - heightMiddle,
        startXMiddle + width,
        startY,
    )
    .fill({ color: colorMiddle })

    // Draw the left mountain
    .moveTo(startXLeft, startY)
    .bezierCurveTo(
        startXLeft + width / 2,
        startY - heightLeft,
        startXLeft + width / 2,
        startY - heightLeft,
        startXLeft + width,
        startY,
    )
    .fill({ color: colorLeft })

    // Draw the right mountain
    .moveTo(startXRight, startY)
    .bezierCurveTo(
        startXRight + width / 2,
        startY - heightRight,
        startXRight + width / 2,
        startY - heightRight,
        startXRight + width,
        startY,
    )
    .fill({ color: colorRight });

return graphics;

Set Up Mountain Groups

With the createMountainGroup() helper function, we can then create 2 instances of the mountain group and offset one of them off the screen to the right.

const group1 = createMountainGroup(app);
const group2 = createMountainGroup(app);

group2.x = app.screen.width;
app.stage.addChild(group1, group2);

You should now see a single group of mountains covering the whole scene.

Animate Mountains

Using the application's ticker, we can add a callback function which will reposition the mountain groups every ticker update, creating a continuous animation. The callback function will be supplied with the Ticker object in which time-related data can be inferred like the deltaTime that we will be using to calculate the distance for the mountain to move consistently. Remember to reposition the groups when they moved completely off the screen.

app.ticker.add((time) =>
{
    const dx = time.deltaTime * 0.5;

    group1.x -= dx;
    group2.x -= dx;

    if (group1.x <= -app.screen.width)
    {
        group1.x += app.screen.width * 2;
    }
    if (group2.x <= -app.screen.width)
    {
        group2.x += app.screen.width * 2;
    }
});
import { Graphics } from 'pixi.js';

export function addTrees(app)
{
    // Width of each tree.
    const treeWidth = 200;

    // Position of the base of the trees on the y-axis.
    const y = app.screen.height - 20;

    // Spacing between each tree.
    const spacing = 15;

    // Calculate the number of trees needed to fill the screen horizontally.
    const count = app.screen.width / (treeWidth + spacing) + 1;

    // Create an array to store all the trees.
    const trees = [];

    for (let index = 0; index < count; index++)
    {
        // Randomize the height of each tree within a constrained range.
        const treeHeight = 225 + Math.random() * 50;

        // Create a tree instance.
        const tree = createTree(treeWidth, treeHeight);

        // Initially position the tree.
        tree.x = index * (treeWidth + spacing);
        tree.y = y;

        // Add the tree to the stage and the reference array.
        app.stage.addChild(tree);
        trees.push(tree);
    }

    // Animate the trees.
    app.ticker.add((time) =>
    {
        // Calculate the amount of distance to move the trees per tick.
        const dx = time.deltaTime * 3;

        trees.forEach((tree) =>
        {
            // Move the trees leftwards.
            tree.x -= dx;

            // Reposition the trees when they move off screen.
            if (tree.x <= -(treeWidth / 2 + spacing))
            {
                tree.x += count * (treeWidth + spacing) + spacing * 3;
            }
        });
    });
}

function createTree(width, height)
{
    // Define the dimensions of the tree trunk.
    const trunkWidth = 30;
    const trunkHeight = height / 4;

    // Define the dimensions and parameters for the tree crown layers.
    const crownHeight = height - trunkHeight;
    const crownLevels = 4;
    const crownLevelHeight = crownHeight / crownLevels;
    const crownWidthIncrement = width / crownLevels;

    // Define the colors of the parts.
    const crownColor = 0x264d3d;
    const trunkColor = 0x563929;

    const graphics = new Graphics()
        // Draw the trunk.
        .rect(-trunkWidth / 2, -trunkHeight, trunkWidth, trunkHeight)
        .fill({ color: trunkColor });

    for (let index = 0; index < crownLevels; index++)
    {
        const y = -trunkHeight - crownLevelHeight * index;
        const levelWidth = width - crownWidthIncrement * index;
        const offset = index < crownLevels - 1 ? crownLevelHeight / 2 : 0;

        // Draw a crown layer.
        graphics
            .moveTo(-levelWidth / 2, y)
            .lineTo(0, y - crownLevelHeight - offset)
            .lineTo(levelWidth / 2, y)
            .fill({ color: crownColor });
    }

    return graphics;
}
import { Graphics } from 'pixi.js';

export function addTrees(app)
{
    /** -- INSERT CODE HERE -- */
}

function createTree(width, height)
{
    /** -- INSERT CODE HERE -- */
}
import { Application } from 'pixi.js';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addStars } from './addStars';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
})();

Adding Trees

Let's apply the same principles we used on the mountains step and do the same thing for the trees layer.

Create Tree

Starting off with the helper function to create a tree, createTree(width, height) which will instantiate a Graphics element with a tree of specified width and height drawn on. We begin with drawing the trunk using Graphics API's rect(x, y, width, height) method and fill it out with fill(style) method as usual.

const trunkWidth = 30;
const trunkHeight = height / 4;
const trunkColor = 0x563929;
const graphics = new Graphics()
        .rect(-trunkWidth / 2, -trunkHeight, trunkWidth, trunkHeight)
        .fill({ color: trunkColor });

Then for the crown, we will draw 4 stacking triangles with each triangle being thinner as we move upwards and the top triangles slightly overlapping the lower ones. Here's an example of how we can achieve that iteratively:

const crownHeight = height - trunkHeight;
const crownLevels = 4;
const crownLevelHeight = crownHeight / crownLevels;
const crownWidthIncrement = width / crownLevels;
const crownColor = 0x264d3d;

for (let index = 0; index < crownLevels; index++)
{
    const y = -trunkHeight - crownLevelHeight * index;
    const levelWidth = width - crownWidthIncrement * index;
    const offset = index < crownLevels - 1 ? crownLevelHeight / 2 : 0;

    graphics
        .moveTo(-levelWidth / 2, y)
        .lineTo(0, y - crownLevelHeight - offset)
        .lineTo(levelWidth / 2, y)
        .fill({ color: crownColor });
}

return graphics;

Set Up Trees

Now in the addTree() function we can instantiate as many trees as we need to cover the screen horizontally, with a few additions as offscreen buffers.

const treeWidth = 200;
const y = app.screen.height - 20;
const spacing = 15;
const count = app.screen.width / (treeWidth + spacing) + 1;
const trees = [];

for (let index = 0; index < count; index++)
{
    const treeHeight = 225 + Math.random() * 50;
    const tree = createTree(treeWidth, treeHeight);

    tree.x = index * (treeWidth + spacing);
    tree.y = y;

    app.stage.addChild(tree);
    trees.push(tree);
}

Animate Trees

Then do the same animation animation setup as we did for the mountains using the application's ticker. However, we will make the rate of change (dx) faster than that of the mountains to simulate the trees being closer to the camera, which should make them go by faster due to the parallax effect.

app.ticker.add((time) =>
{
    const dx = time.deltaTime * 3;

    trees.forEach((tree) =>
    {
        tree.x -= dx;

        if (tree.x <= -(treeWidth / 2 + spacing))
        {
            tree.x += count * (treeWidth + spacing) + spacing * 3;
        }
    });
});
import { Graphics } from 'pixi.js';

export function addGround(app)
{
    const width = app.screen.width;

    // Create and draw the bottom ground graphic.
    const groundHeight = 20;
    const groundY = app.screen.height;
    const ground = new Graphics().rect(0, groundY - groundHeight, width, groundHeight).fill({ color: 0xdddddd });

    // Add the ground to the stage.
    app.stage.addChild(ground);

    // Define the total height of the track. Both the planks and the rail layers.
    const trackHeight = 15;

    // Define the dimensions and parameters for the planks.
    const plankWidth = 50;
    const plankHeight = trackHeight / 2;
    const plankGap = 20;
    const plankCount = width / (plankWidth + plankGap) + 1;
    const plankY = groundY - groundHeight;

    // Create an array to store all the planks.
    const planks = [];

    for (let index = 0; index < plankCount; index++)
    {
        // Create and draw a plank graphic.
        const plank = new Graphics().rect(0, plankY - plankHeight, plankWidth, plankHeight).fill({ color: 0x241811 });

        // Position the plank to distribute it across the screen.
        plank.x = index * (plankWidth + plankGap);

        // Add the plank to the stage and the reference array.
        app.stage.addChild(plank);
        planks.push(plank);
    }

    // Create and draw the rail strip graphic.
    const railHeight = trackHeight / 2;
    const railY = plankY - plankHeight;
    const rail = new Graphics().rect(0, railY - railHeight, width, railHeight).fill({ color: 0x5c5c5c });

    // Add the rail to the stage.
    app.stage.addChild(rail);

    // Animate just the planks to simulate the passing of the ground.
    // Since the rail and the ground are uniform strips, they do not need to be animated.
    app.ticker.add((time) =>
    {
        // Calculate the amount of distance to move the planks per tick.
        const dx = time.deltaTime * 6;

        planks.forEach((plank) =>
        {
            // Move the planks leftwards.
            plank.x -= dx;

            // Reposition the planks when they move off screen.
            if (plank.x <= -(plankWidth + plankGap))
            {
                plank.x += plankCount * (plankWidth + plankGap) + plankGap * 1.5;
            }
        });
    });
}
import { Graphics } from 'pixi.js';

export function addGround(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application } from 'pixi.js';
import { addGround } from './addGround';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addStars } from './addStars';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
    addGround(app);
})();

Adding Ground

The trees are floating in space right at this point, but that's because we left some space for the ground layer. Let's fill that up together now!

We will be making 3 layers of the ground with the bottom-most being the snow and the top two being the train track parts.

Snow Layer

For this, we can simply draw a long rectangle strip across the screen and fill in the color of the snow.

const width = app.screen.width;
const groundHeight = 20;
const groundY = app.screen.height;
const ground = new Graphics()
    .rect(0, groundY - groundHeight, width, groundHeight)
    .fill({ color: 0xdddddd });

app.stage.addChild(ground);

Track's Planks

For the planks, we will be doing the same thing as we did for the trees. First by defining the dimensions of each plank and determining the amount needed to cover the width of the scene with a few additional offscreen buffers as we will be animating them as well. We will position them on top of the snow layer.

const trackHeight = 15;
const plankWidth = 50;
const plankHeight = trackHeight / 2;
const plankGap = 20;
const plankCount = width / (plankWidth + plankGap) + 1;
const plankY = groundY - groundHeight;
const planks = [];

for (let index = 0; index < plankCount; index++)
{
    const plank = new Graphics()
        .rect(0, plankY - plankHeight, plankWidth, plankHeight)
        .fill({ color: 0x241811 });

    plank.x = index * (plankWidth + plankGap);
    app.stage.addChild(plank);
    planks.push(plank);
}

Then add the animation to the planks in the similar manner to the trees animation. Again, making the rate of change (dx) even faster than the trees to simulate the track being closer to the camera, and hence travel faster across the screen (Parallax Effect).

app.ticker.add((time) =>
{
    const dx = time.deltaTime * 6;

    planks.forEach((plank) =>
    {
        plank.x -= dx;

        if (plank.x <= -(plankWidth + plankGap))
        {
            plank.x += plankCount * (plankWidth + plankGap) + plankGap * 1.5;
        }
    });
});

Track's Rail

For the metal rail for the train's wheels to go onto, it will be another simple rectangle strip just like the ground and we will place them above the planks layer.

const railHeight = trackHeight / 2;
const railY = plankY - plankHeight;
const rail = new Graphics()
    .rect(0, railY - railHeight, width, railHeight)
    .fill({ color: 0x5c5c5c });

app.stage.addChild(rail);

import { Container, Graphics } from 'pixi.js';

export function addTrain(app, container)
{
    const head = createTrainHead(app);

    // Add the head to the train container.
    container.addChild(head);

    // Add the train container to the stage.
    app.stage.addChild(container);

    const scale = 0.75;

    // Adjust the scaling of the train.
    container.scale.set(scale);

    // Position the train, taking into account the variety of screen width.
    // To keep the train as the main focus, the train is offset slightly to the left of the screen center.
    container.x = app.screen.width / 2 - head.width / 2;
    container.y = app.screen.height - 35 - 55 * scale;
}

function createTrainHead(app)
{
    // Create a container to hold all the train head parts.
    const container = new Container();

    // Define the dimensions of the head front.
    const frontHeight = 100;
    const frontWidth = 140;
    const frontRadius = frontHeight / 2;

    // Define the dimensions of the cabin.
    const cabinHeight = 200;
    const cabinWidth = 150;
    const cabinRadius = 15;

    // Define the dimensions of the chimney.
    const chimneyBaseWidth = 30;
    const chimneyTopWidth = 50;
    const chimneyHeight = 70;
    const chimneyDomeHeight = 25;
    const chimneyTopOffset = (chimneyTopWidth - chimneyBaseWidth) / 2;
    const chimneyStartX = cabinWidth + frontWidth - frontRadius - chimneyBaseWidth;
    const chimneyStartY = -frontHeight;

    // Define the dimensions of the roof.
    const roofHeight = 25;
    const roofExcess = 20;

    // Define the dimensions of the door.
    const doorWidth = cabinWidth * 0.7;
    const doorHeight = cabinHeight * 0.7;
    const doorStartX = (cabinWidth - doorWidth) * 0.5;
    const doorStartY = -(cabinHeight - doorHeight) * 0.5 - doorHeight;

    // Define the dimensions of the window.
    const windowWidth = doorWidth * 0.8;
    const windowHeight = doorHeight * 0.4;
    const offset = (doorWidth - windowWidth) / 2;

    const graphics = new Graphics()
        // Draw the chimney
        .moveTo(chimneyStartX, chimneyStartY)
        .lineTo(chimneyStartX - chimneyTopOffset, chimneyStartY - chimneyHeight + chimneyDomeHeight)
        .quadraticCurveTo(
            chimneyStartX + chimneyBaseWidth / 2,
            chimneyStartY - chimneyHeight - chimneyDomeHeight,
            chimneyStartX + chimneyBaseWidth + chimneyTopOffset,
            chimneyStartY - chimneyHeight + chimneyDomeHeight,
        )
        .lineTo(chimneyStartX + chimneyBaseWidth, chimneyStartY)
        .fill({ color: 0x121212 })

        // Draw the head front
        .roundRect(
            cabinWidth - frontRadius - cabinRadius,
            -frontHeight,
            frontWidth + frontRadius + cabinRadius,
            frontHeight,
            frontRadius,
        )
        .fill({ color: 0x7f3333 })

        // Draw the cabin
        .roundRect(0, -cabinHeight, cabinWidth, cabinHeight, cabinRadius)
        .fill({ color: 0x725f19 })

        // Draw the roof
        .rect(-roofExcess / 2, cabinRadius - cabinHeight - roofHeight, cabinWidth + roofExcess, roofHeight)
        .fill({ color: 0x52431c })

        // Draw the door
        .roundRect(doorStartX, doorStartY, doorWidth, doorHeight, cabinRadius)
        .stroke({ color: 0x52431c, width: 3 })

        // Draw the window
        .roundRect(doorStartX + offset, doorStartY + offset, windowWidth, windowHeight, 10)
        .fill({ color: 0x848484 });

    // Define the dimensions of the wheels.
    const bigWheelRadius = 55;
    const smallWheelRadius = 35;
    const wheelGap = 5;
    const wheelOffsetY = 5;

    // Create all the wheels.
    const backWheel = createTrainWheel(bigWheelRadius);
    const midWheel = createTrainWheel(smallWheelRadius);
    const frontWheel = createTrainWheel(smallWheelRadius);

    // Position the wheels.
    backWheel.x = bigWheelRadius;
    backWheel.y = wheelOffsetY;
    midWheel.x = backWheel.x + bigWheelRadius + smallWheelRadius + wheelGap;
    midWheel.y = backWheel.y + bigWheelRadius - smallWheelRadius;
    frontWheel.x = midWheel.x + smallWheelRadius * 2 + wheelGap;
    frontWheel.y = midWheel.y;

    // Add all the parts to the container.
    container.addChild(graphics, backWheel, midWheel, frontWheel);

    // Animate the wheels - making the big wheel rotate proportionally slower than the small wheels.
    app.ticker.add((time) =>
    {
        const dr = time.deltaTime * 0.15;

        backWheel.rotation += dr * (smallWheelRadius / bigWheelRadius);
        midWheel.rotation += dr;
        frontWheel.rotation += dr;
    });

    return container;
}

function createTrainWheel(radius)
{
    // Define the dimensions of the wheel.
    const strokeThickness = radius / 3;
    const innerRadius = radius - strokeThickness;

    return (
        new Graphics()
            .circle(0, 0, radius)
            // Draw the wheel
            .fill({ color: 0x848484 })
            // Draw the tyre
            .stroke({ color: 0x121212, width: strokeThickness, alignment: 1 })
            // Draw the spokes
            .rect(-strokeThickness / 2, -innerRadius, strokeThickness, innerRadius * 2)
            .rect(-innerRadius, -strokeThickness / 2, innerRadius * 2, strokeThickness)
            .fill({ color: 0x4f4f4f })
    );
}
import { Container, Graphics } from 'pixi.js';

export function addTrain(app, container)
{
    const head = createTrainHead();

    /** -- INSERT CODE HERE -- */
}

function createTrainHead(app)
{
    /** -- INSERT CODE HERE -- */
}

function createTrainWheel(radius)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Container } from 'pixi.js';
import { addGround } from './addGround';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addStars } from './addStars';
import { addTrain } from './addTrain';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Create a container to hold all the train parts.
const trainContainer = new Container();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
    addGround(app);
    addTrain(app, trainContainer);
})();

Adding Train Head

We will start by making the head of the train first, and to do so we will be separating them into parts:

  • Cabin
  • Door
  • Window
  • Roof
  • Front
  • Chimney
  • Wheels

Apart from the wheels, the parts will be drawn using a single Graphics instance. Let wrap all of the logic for this inside the already set-up createTrainHead() function that will return a Container element holding all the parts together.

Body

The body parts includes the cabin with its overlaying door and window topped with a roof, and the protruding front with the chimney on top.

const frontHeight = 100;
const frontWidth = 140;
const frontRadius = frontHeight / 2;

const cabinHeight = 200;
const cabinWidth = 150;
const cabinRadius = 15;

const chimneyBaseWidth = 30;
const chimneyTopWidth = 50;
const chimneyHeight = 70;
const chimneyDomeHeight = 25;
const chimneyTopOffset = (chimneyTopWidth - chimneyBaseWidth) / 2;
const chimneyStartX = cabinWidth + frontWidth - frontRadius - chimneyBaseWidth;
const chimneyStartY = -frontHeight;

const roofHeight = 25;
const roofExcess = 20;

const doorWidth = cabinWidth * 0.7;
const doorHeight = cabinHeight * 0.7;
const doorStartX = (cabinWidth - doorWidth) * 0.5;
const doorStartY = -(cabinHeight - doorHeight) * 0.5 - doorHeight;

const windowWidth = doorWidth * 0.8;
const windowHeight = doorHeight * 0.4;
const offset = (doorWidth - windowWidth) / 2;

const graphics = new Graphics()
    // Draw the chimney
    .moveTo(chimneyStartX, chimneyStartY)
    .lineTo(chimneyStartX - chimneyTopOffset, chimneyStartY - chimneyHeight + chimneyDomeHeight)
    .quadraticCurveTo(
        chimneyStartX + chimneyBaseWidth / 2,
        chimneyStartY - chimneyHeight - chimneyDomeHeight,
        chimneyStartX + chimneyBaseWidth + chimneyTopOffset,
        chimneyStartY - chimneyHeight + chimneyDomeHeight,
    )
    .lineTo(chimneyStartX + chimneyBaseWidth, chimneyStartY)
    .fill({ color: 0x121212 })

    // Draw the head front
    .roundRect(
        cabinWidth - frontRadius - cabinRadius,
        -frontHeight,
        frontWidth + frontRadius + cabinRadius,
        frontHeight,
        frontRadius,
    )
    .fill({ color: 0x7f3333 })

    // Draw the cabin
    .roundRect(0, -cabinHeight, cabinWidth, cabinHeight, cabinRadius)
    .fill({ color: 0x725f19 })

    // Draw the roof
    .rect(-roofExcess / 2, cabinRadius - cabinHeight - roofHeight, cabinWidth + roofExcess, roofHeight)
    .fill({ color: 0x52431c })

    // Draw the door
    .roundRect(doorStartX, doorStartY, doorWidth, doorHeight, cabinRadius)
    .stroke({ color: 0x52431c, width: 3 })

    // Draw the window
    .roundRect(doorStartX + offset, doorStartY + offset, windowWidth, windowHeight, 10)
    .fill({ color: 0x848484 });

Wheels

For the wheels, lets make a helper function that will instantiate individual wheel given a radius. This has been set up for you as the createTrainWheel(radius) function.

Inside a wheel, we can split it further into parts as:

  • Wheel base
  • Tyre surrounding the base
  • Spokes on the base
const strokeThickness = radius / 3;
const innerRadius = radius - strokeThickness;

return (
    new Graphics()
        .circle(0, 0, radius)
        // Draw the wheel
        .fill({ color: 0x848484 })
        // Draw the tyre
        .stroke({ color: 0x121212, width: strokeThickness, alignment: 1 })
        // Draw the spokes
        .rect(-strokeThickness / 2, -innerRadius, strokeThickness, innerRadius * 2)
        .rect(-innerRadius, -strokeThickness / 2, innerRadius * 2, strokeThickness)
        .fill({ color: 0x4f4f4f })
);

Then we can this helper function inside the createTrainHead() function to create the 3 wheels for the train head which include one larger wheel at the back and two standard sized ones in front.

const bigWheelRadius = 55;
const smallWheelRadius = 35;
const wheelGap = 5;
const wheelOffsetY = 5;

const backWheel = createTrainWheel(bigWheelRadius);
const midWheel = createTrainWheel(smallWheelRadius);
const frontWheel = createTrainWheel(smallWheelRadius);

backWheel.x = bigWheelRadius;
backWheel.y = wheelOffsetY;
midWheel.x = backWheel.x + bigWheelRadius + smallWheelRadius + wheelGap;
midWheel.y = backWheel.y + bigWheelRadius - smallWheelRadius;
frontWheel.x = midWheel.x + smallWheelRadius * 2 + wheelGap;
frontWheel.y = midWheel.y;

Combine and Animate

Now that we have the Graphics instance of the train head's body and its wheels, let add them all onto a wrapping container and then animate the spinning of the wheels before returning the container as the result. Notice here that we make the back wheel rotate proportionally slower like it logically should as it's bigger with more circumference to cover in a revolution.

const container = new Container();

container.addChild(graphics, backWheel, midWheel, frontWheel);

app.ticker.add((time) =>
{
    const dr = time.deltaTime * 0.15;

    backWheel.rotation += dr * (smallWheelRadius / bigWheelRadius);
    midWheel.rotation += dr;
    frontWheel.rotation += dr;
});

return container;


```javascript src/tutorials/v8.0.0/chooChooTrain/step8/addTrain-completed.js
import { Container, Graphics } from 'pixi.js';

export function addTrain(app, container)
{
    const head = createTrainHead(app);
    const carriage = createTrainCarriage(app);

    // Position the carriage behind the head.
    carriage.x = -carriage.width;

    // Add the head and the carriage to the train container.
    container.addChild(head, carriage);

    // Add the train container to the stage.
    app.stage.addChild(container);

    const scale = 0.75;

    // Adjust the scaling of the train.
    container.scale.set(scale);

    // Position the train on the x-axis, taking into account the variety of screen width.
    // To keep the train as the main focus, the train is offset slightly to the left of the screen center.
    container.x = app.screen.width / 2 - head.width / 2;

    // Define animation parameters.
    let elapsed = 0;
    const shakeDistance = 3;
    const baseY = app.screen.height - 35 - 55 * scale;
    const speed = 0.5;

    // Initially position the train on the y-axis.
    container.y = baseY;

    // Animate the train - bobbing it up and down a tiny bit on the track.
    app.ticker.add((time) =>
    {
        elapsed += time.deltaTime;
        const offset = (Math.sin(elapsed * 0.5 * speed) * 0.5 + 0.5) * shakeDistance;

        container.y = baseY + offset;
    });
}

function createTrainHead(app)
{
    // Create a container to hold all the train head parts.
    const container = new Container();

    // Define the dimensions of the head front.
    const frontHeight = 100;
    const frontWidth = 140;
    const frontRadius = frontHeight / 2;

    // Define the dimensions of the cabin.
    const cabinHeight = 200;
    const cabinWidth = 150;
    const cabinRadius = 15;

    // Define the dimensions of the chimney.
    const chimneyBaseWidth = 30;
    const chimneyTopWidth = 50;
    const chimneyHeight = 70;
    const chimneyDomeHeight = 25;
    const chimneyTopOffset = (chimneyTopWidth - chimneyBaseWidth) / 2;
    const chimneyStartX = cabinWidth + frontWidth - frontRadius - chimneyBaseWidth;
    const chimneyStartY = -frontHeight;

    // Define the dimensions of the roof.
    const roofHeight = 25;
    const roofExcess = 20;

    // Define the dimensions of the door.
    const doorWidth = cabinWidth * 0.7;
    const doorHeight = cabinHeight * 0.7;
    const doorStartX = (cabinWidth - doorWidth) * 0.5;
    const doorStartY = -(cabinHeight - doorHeight) * 0.5 - doorHeight;

    // Define the dimensions of the window.
    const windowWidth = doorWidth * 0.8;
    const windowHeight = doorHeight * 0.4;
    const offset = (doorWidth - windowWidth) / 2;

    const graphics = new Graphics()
        // Draw the chimney
        .moveTo(chimneyStartX, chimneyStartY)
        .lineTo(chimneyStartX - chimneyTopOffset, chimneyStartY - chimneyHeight + chimneyDomeHeight)
        .quadraticCurveTo(
            chimneyStartX + chimneyBaseWidth / 2,
            chimneyStartY - chimneyHeight - chimneyDomeHeight,
            chimneyStartX + chimneyBaseWidth + chimneyTopOffset,
            chimneyStartY - chimneyHeight + chimneyDomeHeight,
        )
        .lineTo(chimneyStartX + chimneyBaseWidth, chimneyStartY)
        .fill({ color: 0x121212 })

        // Draw the head front
        .roundRect(
            cabinWidth - frontRadius - cabinRadius,
            -frontHeight,
            frontWidth + frontRadius + cabinRadius,
            frontHeight,
            frontRadius,
        )
        .fill({ color: 0x7f3333 })

        // Draw the cabin
        .roundRect(0, -cabinHeight, cabinWidth, cabinHeight, cabinRadius)
        .fill({ color: 0x725f19 })

        // Draw the roof
        .rect(-roofExcess / 2, cabinRadius - cabinHeight - roofHeight, cabinWidth + roofExcess, roofHeight)
        .fill({ color: 0x52431c })

        // Draw the door
        .roundRect(doorStartX, doorStartY, doorWidth, doorHeight, cabinRadius)
        .stroke({ color: 0x52431c, width: 3 })

        // Draw the window
        .roundRect(doorStartX + offset, doorStartY + offset, windowWidth, windowHeight, 10)
        .fill({ color: 0x848484 });

    // Define the dimensions of the wheels.
    const bigWheelRadius = 55;
    const smallWheelRadius = 35;
    const wheelGap = 5;
    const wheelOffsetY = 5;

    // Create all the wheels.
    const backWheel = createTrainWheel(bigWheelRadius);
    const midWheel = createTrainWheel(smallWheelRadius);
    const frontWheel = createTrainWheel(smallWheelRadius);

    // Position the wheels.
    backWheel.x = bigWheelRadius;
    backWheel.y = wheelOffsetY;
    midWheel.x = backWheel.x + bigWheelRadius + smallWheelRadius + wheelGap;
    midWheel.y = backWheel.y + bigWheelRadius - smallWheelRadius;
    frontWheel.x = midWheel.x + smallWheelRadius * 2 + wheelGap;
    frontWheel.y = midWheel.y;

    // Add all the parts to the container.
    container.addChild(graphics, backWheel, midWheel, frontWheel);

    // Animate the wheels - making the big wheel rotate proportionally slower than the small wheels.
    app.ticker.add((time) =>
    {
        const dr = time.deltaTime * 0.15;

        backWheel.rotation += dr * (smallWheelRadius / bigWheelRadius);
        midWheel.rotation += dr;
        frontWheel.rotation += dr;
    });

    return container;
}

function createTrainCarriage(app)
{
    // Create a container to hold all the train carriage parts.
    const container = new Container();

    // Define the dimensions of the carriage parts.
    const containerHeight = 125;
    const containerWidth = 200;
    const containerRadius = 15;
    const edgeHeight = 25;
    const edgeExcess = 20;
    const connectorWidth = 30;
    const connectorHeight = 10;
    const connectorGap = 10;
    const connectorOffsetY = 20;

    const graphics = new Graphics()
        // Draw the body
        .roundRect(edgeExcess / 2, -containerHeight, containerWidth, containerHeight, containerRadius)
        .fill({ color: 0x725f19 })

        // Draw the top edge
        .rect(0, containerRadius - containerHeight - edgeHeight, containerWidth + edgeExcess, edgeHeight)
        .fill({ color: 0x52431c })

        // Draw the connectors
        .rect(containerWidth + edgeExcess / 2, -connectorOffsetY - connectorHeight, connectorWidth, connectorHeight)
        .rect(
            containerWidth + edgeExcess / 2,
            -connectorOffsetY - connectorHeight * 2 - connectorGap,
            connectorWidth,
            connectorHeight,
        )
        .fill({ color: 0x121212 });

    // Define the dimensions of the wheels.
    const wheelRadius = 35;
    const wheelGap = 40;
    const centerX = (containerWidth + edgeExcess) / 2;
    const offsetX = wheelRadius + wheelGap / 2;

    // Create the wheels.
    const backWheel = createTrainWheel(wheelRadius);
    const frontWheel = createTrainWheel(wheelRadius);

    // Position the wheels.
    backWheel.x = centerX - offsetX;
    frontWheel.x = centerX + offsetX;
    frontWheel.y = backWheel.y = 25;

    // Add all the parts to the container.
    container.addChild(graphics, backWheel, frontWheel);

    // Animate the wheels.
    app.ticker.add((time) =>
    {
        const dr = time.deltaTime * 0.15;

        backWheel.rotation += dr;
        frontWheel.rotation += dr;
    });

    return container;
}

function createTrainWheel(radius)
{
    // Define the dimensions of the wheel.
    const strokeThickness = radius / 3;
    const innerRadius = radius - strokeThickness;

    return (
        new Graphics()
            .circle(0, 0, radius)
            // Draw the wheel
            .fill({ color: 0x848484 })
            // Draw the tyre
            .stroke({ color: 0x121212, width: strokeThickness, alignment: 1 })
            // Draw the spokes
            .rect(-strokeThickness / 2, -innerRadius, strokeThickness, innerRadius * 2)
            .rect(-innerRadius, -strokeThickness / 2, innerRadius * 2, strokeThickness)
            .fill({ color: 0x4f4f4f })
    );
}
import { Container, Graphics } from 'pixi.js';

export function addTrain(app, container)
{
    const head = createTrainHead(app);
    const carriage = createTrainCarriage(app);

    /** -- ADJUST CODE HERE -- */

    // Add the head to the train container.
    container.addChild(head);

    // Add the train container to the stage.
    app.stage.addChild(container);

    const scale = 0.75;

    // Adjust the scaling of the train.
    container.scale.set(scale);

    // Position the train, taking into account the variety of screen width.
    // To keep the train as the main focus, the train is offset slightly to the left of the screen center.
    container.x = app.screen.width / 2 - head.width / 2;
    container.y = app.screen.height - 35 - 55 * scale;
}

function createTrainHead(app)
{
    // Create a container to hold all the train head parts.
    const container = new Container();

    // Define the dimensions of the head front.
    const frontHeight = 100;
    const frontWidth = 140;
    const frontRadius = frontHeight / 2;

    // Define the dimensions of the cabin.
    const cabinHeight = 200;
    const cabinWidth = 150;
    const cabinRadius = 15;

    // Define the dimensions of the chimney.
    const chimneyBaseWidth = 30;
    const chimneyTopWidth = 50;
    const chimneyHeight = 70;
    const chimneyDomeHeight = 25;
    const chimneyTopOffset = (chimneyTopWidth - chimneyBaseWidth) / 2;
    const chimneyStartX = cabinWidth + frontWidth - frontRadius - chimneyBaseWidth;
    const chimneyStartY = -frontHeight;

    // Define the dimensions of the roof.
    const roofHeight = 25;
    const roofExcess = 20;

    // Define the dimensions of the door.
    const doorWidth = cabinWidth * 0.7;
    const doorHeight = cabinHeight * 0.7;
    const doorStartX = (cabinWidth - doorWidth) * 0.5;
    const doorStartY = -(cabinHeight - doorHeight) * 0.5 - doorHeight;

    // Define the dimensions of the window.
    const windowWidth = doorWidth * 0.8;
    const windowHeight = doorHeight * 0.4;
    const offset = (doorWidth - windowWidth) / 2;

    const graphics = new Graphics()
        // Draw the chimney
        .moveTo(chimneyStartX, chimneyStartY)
        .lineTo(chimneyStartX - chimneyTopOffset, chimneyStartY - chimneyHeight + chimneyDomeHeight)
        .quadraticCurveTo(
            chimneyStartX + chimneyBaseWidth / 2,
            chimneyStartY - chimneyHeight - chimneyDomeHeight,
            chimneyStartX + chimneyBaseWidth + chimneyTopOffset,
            chimneyStartY - chimneyHeight + chimneyDomeHeight,
        )
        .lineTo(chimneyStartX + chimneyBaseWidth, chimneyStartY)
        .fill({ color: 0x121212 })

        // Draw the head front
        .roundRect(
            cabinWidth - frontRadius - cabinRadius,
            -frontHeight,
            frontWidth + frontRadius + cabinRadius,
            frontHeight,
            frontRadius,
        )
        .fill({ color: 0x7f3333 })

        // Draw the cabin
        .roundRect(0, -cabinHeight, cabinWidth, cabinHeight, cabinRadius)
        .fill({ color: 0x725f19 })

        // Draw the roof
        .rect(-roofExcess / 2, cabinRadius - cabinHeight - roofHeight, cabinWidth + roofExcess, roofHeight)
        .fill({ color: 0x52431c })

        // Draw the door
        .roundRect(doorStartX, doorStartY, doorWidth, doorHeight, cabinRadius)
        .stroke({ color: 0x52431c, width: 3 })

        // Draw the window
        .roundRect(doorStartX + offset, doorStartY + offset, windowWidth, windowHeight, 10)
        .fill({ color: 0x848484 });

    // Define the dimensions of the wheels.
    const bigWheelRadius = 55;
    const smallWheelRadius = 35;
    const wheelGap = 5;
    const wheelOffsetY = 5;

    // Create all the wheels.
    const backWheel = createTrainWheel(bigWheelRadius);
    const midWheel = createTrainWheel(smallWheelRadius);
    const frontWheel = createTrainWheel(smallWheelRadius);

    // Position the wheels.
    backWheel.x = bigWheelRadius;
    backWheel.y = wheelOffsetY;
    midWheel.x = backWheel.x + bigWheelRadius + smallWheelRadius + wheelGap;
    midWheel.y = backWheel.y + bigWheelRadius - smallWheelRadius;
    frontWheel.x = midWheel.x + smallWheelRadius * 2 + wheelGap;
    frontWheel.y = midWheel.y;

    // Add all the parts to the container.
    container.addChild(graphics, backWheel, midWheel, frontWheel);

    // Animate the wheels - making the big wheel rotate proportionally slower than the small wheels.
    app.ticker.add((time) =>
    {
        const dr = time.deltaTime * 0.15;

        backWheel.rotation += dr * (smallWheelRadius / bigWheelRadius);
        midWheel.rotation += dr;
        frontWheel.rotation += dr;
    });

    return container;
}

function createTrainCarriage(app)
{
    /** -- INSERT CODE HERE -- */
}

function createTrainWheel(radius)
{
    // Define the dimensions of the wheel.
    const strokeThickness = radius / 3;
    const innerRadius = radius - strokeThickness;

    return (
        new Graphics()
            .circle(0, 0, radius)
            // Draw the wheel
            .fill({ color: 0x848484 })
            // Draw the tyre
            .stroke({ color: 0x121212, width: strokeThickness, alignment: 1 })
            // Draw the spokes
            .rect(-strokeThickness / 2, -innerRadius, strokeThickness, innerRadius * 2)
            .rect(-innerRadius, -strokeThickness / 2, innerRadius * 2, strokeThickness)
            .fill({ color: 0x4f4f4f })
    );
}
import { Application, Container } from 'pixi.js';
import { addGround } from './addGround';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addStars } from './addStars';
import { addTrain } from './addTrain';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Create a container to hold all the train parts.
const trainContainer = new Container();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
    addGround(app);
    addTrain(app, trainContainer);
})();

Adding Train Carriage

Accompanying the head, let's add a trailing carriage to complete a running train. Here we will be doing the same procedures as when we were building the head inside the new createTrainCarriage() function. The carriage consists of 4 parts:

  • Container
  • Top Edge
  • Connectors
  • Wheels

We can re-use the createTrainWheel(radius) function to create the two standard sized wheels which will be animated in the same manner as before.

const container = new Container();

const containerHeight = 125;
const containerWidth = 200;
const containerRadius = 15;
const edgeHeight = 25;
const edgeExcess = 20;
const connectorWidth = 30;
const connectorHeight = 10;
const connectorGap = 10;
const connectorOffsetY = 20;

const graphics = new Graphics()
    // Draw the body
    .roundRect(edgeExcess / 2, -containerHeight, containerWidth, containerHeight, containerRadius)
    .fill({ color: 0x725f19 })

    // Draw the top edge
    .rect(0, containerRadius - containerHeight - edgeHeight, containerWidth + edgeExcess, edgeHeight)
    .fill({ color: 0x52431c })

    // Draw the connectors
    .rect(containerWidth + edgeExcess / 2, -connectorOffsetY - connectorHeight, connectorWidth, connectorHeight)
    .rect(
        containerWidth + edgeExcess / 2,
        -connectorOffsetY - connectorHeight * 2 - connectorGap,
        connectorWidth,
        connectorHeight,
    )
    .fill({ color: 0x121212 });

const wheelRadius = 35;
const wheelGap = 40;
const centerX = (containerWidth + edgeExcess) / 2;
const offsetX = wheelRadius + wheelGap / 2;

const backWheel = createTrainWheel(wheelRadius);
const frontWheel = createTrainWheel(wheelRadius);

backWheel.x = centerX - offsetX;
frontWheel.x = centerX + offsetX;
frontWheel.y = backWheel.y = 25;

container.addChild(graphics, backWheel, frontWheel);

app.ticker.add((time) =>
{
    const dr = time.deltaTime * 0.15;

    backWheel.rotation += dr;
    frontWheel.rotation += dr;
});

return container;

Assemble Train

With the createTrainHead() and createTrainCarriage() functions completed, let's use them to create the sections, adding them to a wrapping container, offsetting the trailing carriage to be behind the train head. We can then top it up with a little bobble up and down to simulate shaking due to the travel along the track.

const head = createTrainHead();
const carriage = createTrainCarriage();

carriage.x = -carriage.width;

trainContainer.addChild(head, carriage);
app.stage.addChild(trainContainer);

const scale = 0.75;

trainContainer.scale.set(scale);
trainContainer.x = app.screen.width / 2 - head.width / 2;

let elapsed = 0;
const shakeDistance = 3;
const baseY = app.screen.height - 35 - 55 * scale;
const speed = 0.5;

trainContainer.y = baseY;

app.ticker.add((time) =>
{
    elapsed += time.deltaTime;
    const offset = (Math.sin(elapsed * 0.5 * speed) * 0.5 + 0.5) * shakeDistance;

    trainContainer.y = baseY + offset;
});
import { Graphics } from 'pixi.js';

export function addSmokes(app, train)
{
    const groupCount = 5;
    const particleCount = 7;

    // Create an array to store all the smoke groups.
    const groups = [];

    // Define the emitter position based on the train's position.
    const baseX = train.x + 170;
    const baseY = train.y - 120;

    for (let index = 0; index < groupCount; index++)
    {
        const smokeGroup = new Graphics();

        for (let i = 0; i < particleCount; i++)
        {
            // Randomize the position and radius of each particle.
            const radius = 20 + Math.random() * 20;
            const x = (Math.random() * 2 - 1) * 40;
            const y = (Math.random() * 2 - 1) * 40;

            // Draw a smoke particle.
            smokeGroup.circle(x, y, radius);
        }

        // Fill the smoke group with gray color.
        smokeGroup.fill({ color: 0xc9c9c9 });

        // Position the smoke group.
        smokeGroup.x = baseX;
        smokeGroup.y = baseY;

        // Add a tick custom property to the smoke group for storing the animation progress ratio.
        smokeGroup.tick = index * (1 / groupCount);

        // Add the smoke group to the stage and the reference array.
        app.stage.addChild(smokeGroup);
        groups.push(smokeGroup);
    }

    // Animate the smoke groups.
    app.ticker.add((time) =>
    {
        // Calculate the change in amount of animation progress ratio per tick.
        const dt = time.deltaTime * 0.01;

        groups.forEach((group) =>
        {
            // Update the animation progress ratio.
            group.tick = (group.tick + dt) % 1;

            // Update the position and scale of the smoke group based on the animation progress ratio.
            group.x = baseX - Math.pow(group.tick, 2) * 400;
            group.y = baseY - group.tick * 200;
            group.scale.set(Math.pow(group.tick, 0.75));
            group.alpha = 1 - Math.pow(group.tick, 0.5);
        });
    });
}
import { Graphics } from 'pixi.js';

export function addSmokes(app, train)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Container } from 'pixi.js';
import { addGround } from './addGround';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addSmokes } from './addSmokes';
import { addStars } from './addStars';
import { addTrain } from './addTrain';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Create a container to hold all the train parts.
const trainContainer = new Container();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
    addGround(app);
    addTrain(app, trainContainer);
    addSmokes(app, trainContainer);
})();

Adding Smokes

For the final touch, let's create groups of smoke particles animating in from the train chimney and out off the screen.

Create Smoke Groups

First we need to create the individual groups of circular particles of varying size and position within the cluster, each group under a single Graphics instance. For the purpose of animation, we then assign a custom tick property to each group which will be used to reference the percentage of the animation from the chimney to the disappearing point.

const groupCount = 5;
const particleCount = 7;
const groups = [];
const baseX = trainContainer.x + 170;
const baseY = trainContainer.y - 120;

for (let index = 0; index < groupCount; index++)
{
    const smokeGroup = new Graphics();

    for (let i = 0; i < particleCount; i++)
    {
        const radius = 20 + Math.random() * 20;
        const x = (Math.random() * 2 - 1) * 40;
        const y = (Math.random() * 2 - 1) * 40;

        smokeGroup.circle(x, y, radius);
    }

    smokeGroup.fill({ color: 0xc9c9c9, alpha: 0.5 });

    smokeGroup.x = baseX;
    smokeGroup.y = baseY;
    smokeGroup.tick = index * (1 / groupCount);

    groups.push(smokeGroup);
}

Animate Smokes

As you can see, we previously offset the tick value on each group initially to distribute them out so that it illustrates the constant line of smokes coming out from the chimney. We then use the same technique of using the application's ticker for the animation, incrementing the tick value on all groups which is then used to calculate the position and scale of each. The value is modulated so that it goes back to the starting point when it finishes at the disappearing point, ie. the value will loop infinitely from 0 -> 1.

app.ticker.add((time) =>
{
    const dt = time.deltaTime * 0.01;

    groups.forEach((group) =>
    {
        group.tick = (group.tick + dt) % 1;
        group.x = baseX - Math.pow(group.tick, 2) * 400;
        group.y = baseY - group.tick * 200;
        group.scale.set(Math.pow(group.tick, 0.75));
    });
});
import { Application, Container } from 'pixi.js';
import { addGround } from './addGround';
import { addMoon } from './addMoon';
import { addMountains } from './addMountains';
import { addSmokes } from './addSmokes';
import { addStars } from './addStars';
import { addTrain } from './addTrain';
import { addTrees } from './addTrees';

// Create a PixiJS application.
const app = new Application();

// Create a container to hold all the train parts.
const trainContainer = new Container();

// Asynchronous IIFE
(async () =>
{
    // Intialize the application.
    await app.init({ background: '#021f4b', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    addStars(app);
    addMoon(app);
    addMountains(app);
    addTrees(app);
    addGround(app);
    addTrain(app, trainContainer);
    addSmokes(app, trainContainer);
})();

You did it!

Congratulations, hope you enjoyed the journey! Now you are an expert on the Graphics API. Make sure to explore other features that the API has to offer on the official documentation, like the ability to cut shapes out from existing ones, advance lines and curves, using gradients or textures for fill and stroke - just to list a few.

Feel free to head back to the gallery and explore other tutorials.

Fish Pond Example

import { Application, Assets } from 'pixi.js';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();
})();

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}
import { Application, Assets } from 'pixi.js';

// Create a PixiJS application.
const app = new Application();

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();
})();

async function setup()
{
    /** -- INSERT CODE HERE -- */
}

async function preload()
{
    /** -- INSERT CODE HERE -- */
}

Let's make a pond!

Welcome to the Fish Pond workshop!

We are going to build a virtual pond and fill them with a number of colorful fishes. In the process, we will be learning about basic manipulation of Sprites, TilingSprite and Filter, specifically the Displacement Filter.

Please go through the tutorial steps at your own pace and challenge yourself using the editor on the right hand side. Here PixiJS has already been included as guided under the Getting Started section. Let's start off by creation a PixiJS application, initialize it, add its canvas to the DOM, and preload the required assets ahead of the subsequent steps.

We will be using an asynchronous immediately invoked function expression (IIFE), but you are free to switch to use promises instead.

Application Setup

Let's create the application outside of the IIFE just so that it can be referenced across other functions declared outside. The initialization and appending the application's canvas will be done from within the setup function which is called inside the IIFE.

async function setup()
{
    await app.init({ background: '#1099bb', resizeTo: window });
    document.body.appendChild(app.canvas);
}

Preloading Assets

After the application setup, we will then preload all the textures required for the rest of the tutorial. Here we also provide aliases so that they can be intuitively referred to later on. This will be done inside the preload function which is also called inside the IIFE after the setup.

async function preload()
{
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];
    await Assets.load(assets);
}

At this point, you should see the preview filled with an empty light blue background.

When you are ready, proceed to the next exercise using the Next > button below, or feel free to skip to any exercise using the drop-down menu on the top right hand corner of the card.

import { Sprite } from 'pixi.js';

export function addBackground(app)
{
    // Create a background sprite.
    const background = Sprite.from('background');

    // Center background sprite anchor.
    background.anchor.set(0.5);

    /**
     * If the preview is landscape, fill the width of the screen
     * and apply horizontal scale to the vertical scale for a uniform fit.
     */
    if (app.screen.width > app.screen.height)
    {
        background.width = app.screen.width * 1.2;
        background.scale.y = background.scale.x;
    }
    else
    {
        /**
         * If the preview is square or portrait, then fill the height of the screen instead
         * and apply the scaling to the horizontal scale accordingly.
         */
        background.height = app.screen.height * 1.2;
        background.scale.x = background.scale.y;
    }

    // Position the background sprite in the center of the stage.
    background.x = app.screen.width / 2;
    background.y = app.screen.height / 2;

    // Add the background to the stage.
    app.stage.addChild(background);
}
import { Sprite } from 'pixi.js';

export function addBackground(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Assets } from 'pixi.js';
import { addBackground } from './addBackground';

// Create a PixiJS application.
const app = new Application();

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();

    addBackground(app);
})();

Adding a Background

Now lets fill the pond with some rocks and pebbles, shall we? Let's work inside the already prepared addBackground function.

Create and Setup Background Sprite

We already preloaded the pond background asset as the alias 'background' so we can just simply create a sprite

const background = Sprite.from('background');

background.anchor.set(0.5);

Fit and Position Sprite

Now we want the background sprite to fill the whole screen without any distortion so we will compare and fill the longer axis and then apply the same scale on the smaller axis for a uniform scaling.

(Note: x1.2 scaling to the dimension is to overflow the screen slightly to compensate for the last's step distortion from post-processing)

if (app.screen.width > app.screen.height)
{
    background.width = app.screen.width * 1.2;
    background.scale.y = background.scale.x;
}
else
{
    background.height = app.screen.height  * 1.2;
    background.scale.x = background.scale.y;
}

When we manually set the width or height on a sprite, it will apply a scale on the corresponding axis depending on the width or height of the original texture. Hence, we can simply equalize the scale on both axes this way.

Then we simply position it at the center of the preview.

background.x = app.screen.width / 2;
background.y = app.screen.height / 2;

Finally, we'll add our new background to the Scene Graph of our application:

app.stage.addChild(background);

We got a beautiful pond! Now let's proceed to add some fishes!

import { Container, Sprite } from 'pixi.js';

export function addFishes(app, fishes)
{
    // Create a container to hold all the fish sprites.
    const fishContainer = new Container();

    // Add the fish container to the stage.
    app.stage.addChild(fishContainer);

    const fishCount = 20;
    const fishAssets = ['fish1', 'fish2', 'fish3', 'fish4', 'fish5'];

    // Create a fish sprite for each fish.
    for (let i = 0; i < fishCount; i++)
    {
        // Cycle through the fish assets for each sprite.
        const fishAsset = fishAssets[i % fishAssets.length];

        // Create a fish sprite.
        const fish = Sprite.from(fishAsset);

        // Center the sprite anchor.
        fish.anchor.set(0.5);

        // Assign additional properties for the animation.
        fish.direction = Math.random() * Math.PI * 2;
        fish.speed = 2 + Math.random() * 2;
        fish.turnSpeed = Math.random() - 0.8;

        // Randomly position the fish sprite around the stage.
        fish.x = Math.random() * app.screen.width;
        fish.y = Math.random() * app.screen.height;

        // Randomly scale the fish sprite to create some variety.
        fish.scale.set(0.5 + Math.random() * 0.2);

        // Add the fish sprite to the fish container.
        fishContainer.addChild(fish);

        // Add the fish sprite to the fish array.
        fishes.push(fish);
    }
}

export function animateFishes(app, fishes, time)
{
    // Extract the delta time from the Ticker object.
    const delta = time.deltaTime;

    // Define the padding around the stage where fishes are considered out of sight.
    const stagePadding = 100;
    const boundWidth = app.screen.width + stagePadding * 2;
    const boundHeight = app.screen.height + stagePadding * 2;

    // Iterate through each fish sprite.
    fishes.forEach((fish) =>
    {
        // Animate the fish movement direction according to the turn speed.
        fish.direction += fish.turnSpeed * 0.01;

        // Animate the fish position according to the direction and speed.
        fish.x += Math.sin(fish.direction) * fish.speed;
        fish.y += Math.cos(fish.direction) * fish.speed;

        // Apply the fish rotation according to the direction.
        fish.rotation = -fish.direction - Math.PI / 2;

        // Wrap the fish position when it goes out of bounds.
        if (fish.x < -stagePadding)
        {
            fish.x += boundWidth;
        }
        if (fish.x > app.screen.width + stagePadding)
        {
            fish.x -= boundWidth;
        }
        if (fish.y < -stagePadding)
        {
            fish.y += boundHeight;
        }
        if (fish.y > app.screen.height + stagePadding)
        {
            fish.y -= boundHeight;
        }
    });
}
import { Container, Sprite } from 'pixi.js';

export function addFishes(app, fishes)
{
    /** -- INSERT CODE HERE -- */
}

export function animateFishes(app, fishes, time)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Assets } from 'pixi.js';
import { addBackground } from './addBackground';
import { addFishes, animateFishes } from './addFishes';

// Create a PixiJS application.
const app = new Application();

// Store an array of fish sprites for animation.
const fishes = [];

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();

    addBackground(app);
    addFishes(app, fishes);

    // Add the fish animation callback to the application's ticker.
    app.ticker.add((time) => animateFishes(app, fishes, time));
})();

Adding Fishes

What's a pond without the fishes, right? Let's use what we learn from the previous step to add some fish sprites to the scene as well. We will also animate them afterwards to give them life.

Create and Setup Fish Sprites

Let's encapsulate all the following setup within the addFishes function that has already been prepared for you. We begin by creating a container to hold all the fish sprites together and add it to the stage. This is a great practice for better separation.

const fishContainer = new Container();

app.stage.addChild(fishContainer);

Then we declare some reference variables like how many fishes should there be in the pond and what are the fish types available. For the types, we refer to the 5 different fish assets we have preloaded earlier and made them into an array of aliases.

const fishCount = 20;
const fishAssets = ['fish1', 'fish2', 'fish3', 'fish4', 'fish5'];

Instead of creating each of the fish individually, which will be super tedious, we will use a simple for loop to create each of the fish until it reaches our desire count, also cycling through the fish asset aliases array. In addition to the basic setup and applying initial transforms, we also assign them with custom properties like direction, speed and turnSpeed which will be used during the animation. We will store the fishes in a reference array defined outside of the IIFE.

for (let i = 0; i < fishCount; i++)
{
    const fishAsset = fishAssets[i % fishAssets.length];
    const fish = Sprite.from(fishAsset);

    fish.anchor.set(0.5);

    fish.direction = Math.random() * Math.PI * 2;
    fish.speed = 2 + Math.random() * 2;
    fish.turnSpeed = Math.random() - 0.8;

    fish.x = Math.random() * app.screen.width;
    fish.y = Math.random() * app.screen.height;
    fish.scale.set(0.5 + Math.random() * 0.2);

    fishContainer.addChild(fish);
    fishes.push(fish);
}

Animate Fishes

It's time to give the fishes some movements! Another function animateFishes has been prepared and connected to the application's ticker which will be continuously called. It is supplied with a Ticker object which we can use to infer the amount of time passed between the calls.

We will declare a few variables to help us with the animation. We extract deltaTime from the Ticker object which tells us the amount of time passed since last call, in seconds. We also define an imaginary bound that is larger than the stage itself to wrap the position of the fishes when they go off the screen. We use this bound instead of the actual screen size to avoid having the fishes disappear before they actually go off the edges, since the fish sprites' anchor is in the center so, eg. when a fish.x = 0, half of the fish's width is still apparent on the screen.

const delta = time.deltaTime;

const stagePadding = 100;
const boundWidth = app.screen.width + stagePadding * 2;
const boundHeight = app.screen.height + stagePadding * 2;

We can then simply loop through individual fishes array and update them one by one. First by updating the fish's pseudo direction which dictates the changes in its sprite position and rotation. To keep the fish within the screen bound, we use the padded bound defined earlier to check and wrap the fish as soon as it goes off the bound.

fishes.forEach((fish) =>
{
    fish.direction += fish.turnSpeed * 0.01;
    fish.x += Math.sin(fish.direction) * fish.speed;
    fish.y += Math.cos(fish.direction) * fish.speed;
    fish.rotation = -fish.direction - Math.PI / 2;

    if (fish.x < -stagePadding)
    {
        fish.x += boundWidth;
    }
    if (fish.x > app.screen.width + stagePadding)
    {
        fish.x -= boundWidth;
    }
    if (fish.y < -stagePadding)
    {
        fish.y += boundHeight;
    }
    if (fish.y > app.screen.height + stagePadding)
    {
        fish.y -= boundHeight;
    }
});
import { Texture, TilingSprite } from 'pixi.js';

// Reference to the water overlay.
let overlay;

export function addWaterOverlay(app)
{
    // Create a water texture object.
    const texture = Texture.from('overlay');

    // Create a tiling sprite with the water texture and specify the dimensions.
    overlay = new TilingSprite({
        texture,
        width: app.screen.width,
        height: app.screen.height,
    });

    // Add the overlay to the stage.
    app.stage.addChild(overlay);
}

export function animateWaterOverlay(app, time)
{
    // Extract the delta time from the Ticker object.
    const delta = time.deltaTime;

    // Animate the overlay.
    overlay.tilePosition.x -= delta;
    overlay.tilePosition.y -= delta;
}
import { Texture, TilingSprite } from 'pixi.js';

// Reference to the water overlay.
let overlay;

export function addWaterOverlay(app)
{
    /** -- INSERT CODE HERE -- */
}

export function animateWaterOverlay(app, time)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Assets } from 'pixi.js';
import { addBackground } from './addBackground';
import { addFishes, animateFishes } from './addFishes';
import { addWaterOverlay, animateWaterOverlay } from './addWaterOverlay';

// Create a PixiJS application.
const app = new Application();

// Store an array of fish sprites for animation.
const fishes = [];

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();

    addBackground(app);
    addFishes(app, fishes);
    addWaterOverlay(app);

    // Add the animation callbacks to the application's ticker.
    app.ticker.add((time) =>
    {
        animateFishes(app, fishes, time);
        animateWaterOverlay(app, time);
    });
})();

Adding Water Overlay

At the point, the fishes look like they are floating on the rocks and pebbles. We will overlay what we have so far with a tiling sprite of a tiled water texture. Tiling sprite is essentially a sprite with the capabilities of transforming and rending an infinitely repeating grid of a single texture, preferably a tiled one where the edges seamlessly connect with each other when put together. We will use this to give an illusion of a forever moving water surface.

Create and Setup Tiling Sprite

Here we create a tiling sprite, supplying a texture and dimensions as an option object, and add it to the stage.

// Create a water texture object.
const texture = Texture.from('overlay');

// Create a tiling sprite with the water texture and specify the dimensions.
overlay = new TilingSprite({
    texture,
    width: app.screen.width,
    height: app.screen.height,
});

// Add the overlay to the stage.
app.stage.addChild(overlay);

Animate Overlay

Similar to the previous step, we will now animate the water overlay using the application's ticker. The code has been modified to call both animation functions for the fish and this overlay so we only need to add the animation logic inside the animateWaterOverlay function:

// Extract the delta time from the Ticker object.
const delta = time.deltaTime;

// Animate the overlay.
overlay.tilePosition.x -= delta;
overlay.tilePosition.y -= delta;

Congratulations, we have now completed a beautiful pond! But we can take it a step further. Let's proceed to the final touch!

import { DisplacementFilter, Sprite } from 'pixi.js';

export function addDisplacementEffect(app)
{
    // Create a sprite from the preloaded displacement asset.
    const sprite = Sprite.from('displacement');

    // Set the base texture wrap mode to repeat to allow the texture UVs to be tiled and repeated.
    sprite.texture.baseTexture.wrapMode = 'repeat';

    // Create a displacement filter using the sprite texture.
    const filter = new DisplacementFilter({
        sprite,
        scale: 50,
    });

    // Add the filter to the stage.
    app.stage.filters = [filter];
}
import { DisplacementFilter, Sprite } from 'pixi.js';

export function addDisplacementEffect(app)
{
    /** -- INSERT CODE HERE -- */
}
import { Application, Assets } from 'pixi.js';
import { addBackground } from './addBackground';
import { addDisplacementEffect } from './addDisplacementEffect';
import { addFishes, animateFishes } from './addFishes';
import { addWaterOverlay, animateWaterOverlay } from './addWaterOverlay';

// Create a PixiJS application.
const app = new Application();

// Store an array of fish sprites for animation.
const fishes = [];

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();

    addBackground(app);
    addFishes(app, fishes);
    addWaterOverlay(app);
    addDisplacementEffect(app);

    // Add the animation callbacks to the application's ticker.
    app.ticker.add((time) =>
    {
        animateFishes(app, fishes, time);
        animateWaterOverlay(app, time);
    });
})();

Adding Displacement Effect

Let's be a bit extra and simulate distortion effect from the water.

PixiJS comes with a handful of filters built-in and many dozens of fancy ones on the PixiJS Filters package. Here, we will be using the displacement filter for the distortion, which is built-in to the native PixiJS so we do not have to install any additional filter packages.

Displacement filter requires a sprite as a parameter for its options object. We will need to create a sprite from the displacement map asset and set its base texture's wrap mode to be 'repeat' so that the shader can tile and repeated it.

const sprite = Sprite.from('displacement');

sprite.texture.baseTexture.wrapMode = 'repeat';

From here, we can simply create the displacement filter and add it to the stage container's filters list.

const filter = new DisplacementFilter({
    sprite,
    scale: 50,
});

app.stage.filters = [filter];

Now you should see the post-processed pond in effect. Looks like we are looking down directly into a real pond, right?

import { Application, Assets } from 'pixi.js';
import { addBackground } from './addBackground';
import { addDisplacementEffect } from './addDisplacementEffect';
import { addFishes, animateFishes } from './addFishes';
import { addWaterOverlay, animateWaterOverlay } from './addWaterOverlay';

// Create a PixiJS application.
const app = new Application();

// Store an array of fish sprites for animation.
const fishes = [];

async function setup()
{
    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);
}

async function preload()
{
    // Create an array of asset data to load.
    const assets = [
        { alias: 'background', src: 'https://pixijs.com/assets/tutorials/fish-pond/pond_background.jpg' },
        { alias: 'fish1', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish1.png' },
        { alias: 'fish2', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish2.png' },
        { alias: 'fish3', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish3.png' },
        { alias: 'fish4', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish4.png' },
        { alias: 'fish5', src: 'https://pixijs.com/assets/tutorials/fish-pond/fish5.png' },
        { alias: 'overlay', src: 'https://pixijs.com/assets/tutorials/fish-pond/wave_overlay.png' },
        { alias: 'displacement', src: 'https://pixijs.com/assets/tutorials/fish-pond/displacement_map.png' },
    ];

    // Load the assets defined above.
    await Assets.load(assets);
}

// Asynchronous IIFE
(async () =>
{
    await setup();
    await preload();

    addBackground(app);
    addFishes(app, fishes);
    addWaterOverlay(app);
    addDisplacementEffect(app);

    // Add the animation callbacks to the application's ticker.
    app.ticker.add((time) =>
    {
        animateFishes(app, fishes, time);
        animateWaterOverlay(app, time);
    });
})();

You did it!

Spine Boy Adventure Example

import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);
})();

SpineBoy Adventure

Welcome to the SpineBoy Adventure workshop!

Let's venture into the world of the PixiJS ecosystem. We are going to explore one of the official plugins; Spine plugin (@esotericsoftware/spine-pixi-v8) which allow us to render and manipulate Spine animations on our PixiJS.

We will be creating a mini interactive side-scroller experience using the famous SpineBoy which will be controlled by the keyboard. For the sake of simplicity, we will be focusing on just the movement around the scene.

What is Spine

Spine, developed by Esoteric Software, is a 2D animation software specifically designed for games. It streamlines 2D game animation with skeletal animation, robust tools, and exportable, lightweight animations.

Application Setup

As usual, let's begin by creating an application, initializing it, and appending its canvas to the DOM inside the IIFE.

await app.init({ background: '#021f4b', resizeTo: window });
document.body.appendChild(app.canvas);

Assets Preloading

Let's then preload all of our required assets upfront which includes:

  1. Spine Assets
    • Skeleton data file.
    • Accompanying ATLAS.
  2. Scene Images
    • Static sky gradient image.
    • Tiled image of the massive buildings in the distance.
    • Tiled image of the city skyline.
    • Tiled image of the platform that the character will be moving on.
await Assets.load([
    {
        alias: 'spineSkeleton',
        src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
    },
    {
        alias: 'spineAtlas',
        src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
    },
    {
        alias: 'sky',
        src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
    },
    {
        alias: 'background',
        src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
    },
    {
        alias: 'midground',
        src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
    },
    {
        alias: 'platform',
        src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
    },
]);

Now you are ready to dive straight into the adventure! Proceed to the next exercise using the Next > button below, or feel free to skip to any exercise using the drop-down menu on the top right hand corner of the card.

import { Container } from 'pixi.js';
import { Spine } from '@esotericsoftware/spine-pixi-v8';

// Class for handling the character Spine and its animations.
export class SpineBoy
{
    constructor()
    {
        // Create the main view.
        this.view = new Container();

        // Create the Spine instance using the preloaded Spine asset aliases.
        this.spine = Spine.from({
            skeleton: 'spineSkeleton',
            atlas: 'spineAtlas',
        });

        // Add the spine to the main view.
        this.view.addChild(this.spine);
    }
}
import { Container } from 'pixi.js';
import { Spine } from '@esotericsoftware/spine-pixi-v8';

// Class for handling the character Spine and its animations.
export class SpineBoy
{
    constructor()
    {
        // Create the main view.
        this.view = new Container();

        /** -- INSERT CODE HERE -- */
    }
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust character transformation.
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - 80;
    spineBoy.spine.scale.set(0.5);

    // Add character to the stage.
    app.stage.addChild(spineBoy.view);
})();
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    /** -- INSERT CODE HERE -- */
})();

Setting Up Character

We will now create a class for containing and handling our character Spine animations.

Here, a `SpineBoy`` class has been set up on a different file. Lets start off by doing the minimum to get the character Spine displayed. Inside the class, a view container has also been set up to hold any of the content from within the class.

We can use the Spine.from(options) method to instantiate our SpineBoy using the preloaded Character's Spine skeleton file and ATLAS file. We then store it as the spine member of the class for future references both internally and externally. And of course, remember to add it to the class' view container.

this.spine = Spine.from({
    skeleton: 'spineSkeleton',
    atlas: 'spineAtlas',
});
this.view.addChild(this.spine);

Let's also create an instance of our SpineBoy class on our main index.js file and add its view to our application's stage. To keep it simple, let just keep our character in the middle of the screen and 80 pixels from the bottom of the screen, and also scale it down a little to ensure the fit.

// Create our character
const spineBoy = new SpineBoy();

// Adjust character transformation.
spineBoy.view.x = app.screen.width / 2;
spineBoy.view.y = app.screen.height - 80;
spineBoy.spine.scale.set(0.5);

// Add character to the stage.
app.stage.addChild(spineBoy.view);
// Map keyboard key codes to controller's state keys
const keyMap = {
    Space: 'space',
    KeyW: 'up',
    ArrowUp: 'up',
    KeyA: 'left',
    ArrowLeft: 'left',
    KeyS: 'down',
    ArrowDown: 'down',
    KeyD: 'right',
    ArrowRight: 'right',
};

// Class for handling keyboard inputs.
export class Controller
{
    constructor()
    {
        // The controller's state.
        this.keys = {
            up: { pressed: false, doubleTap: false, timestamp: 0 },
            left: { pressed: false, doubleTap: false, timestamp: 0 },
            down: { pressed: false, doubleTap: false, timestamp: 0 },
            right: { pressed: false, doubleTap: false, timestamp: 0 },
            space: { pressed: false, doubleTap: false, timestamp: 0 },
        };

        // Register event listeners for keydown and keyup events.
        window.addEventListener('keydown', (event) => this.keydownHandler(event));
        window.addEventListener('keyup', (event) => this.keyupHandler(event));
    }

    keydownHandler(event)
    {
        const key = keyMap[event.code];

        if (!key) return;

        const now = Date.now();

        // If not already in the double-tap state, toggle the double tap state if the key was pressed twice within 300ms.
        this.keys[key].doubleTap = this.keys[key].doubleTap || now - this.keys[key].timestamp < 300;

        // Toggle on the key pressed state.
        this.keys[key].pressed = true;
    }

    keyupHandler(event)
    {
        const key = keyMap[event.code];

        if (!key) return;

        const now = Date.now();

        // Reset the key pressed state.
        this.keys[key].pressed = false;

        // Reset double tap only if the key is in the double-tap state.
        if (this.keys[key].doubleTap) this.keys[key].doubleTap = false;
        // Otherwise, update the timestamp to track the time difference till the next potential key down.
        else this.keys[key].timestamp = now;
    }
}
// Map keyboard key codes to controller's state keys
const keyMap = {
    Space: 'space',
    KeyW: 'up',
    ArrowUp: 'up',
    KeyA: 'left',
    ArrowLeft: 'left',
    KeyS: 'down',
    ArrowDown: 'down',
    KeyD: 'right',
    ArrowRight: 'right',
};

// Class for handling keyboard inputs.
export class Controller
{
    constructor()
    {
        // The controller's state.
        this.keys = {
            up: { pressed: false, doubleTap: false, timestamp: 0 },
            left: { pressed: false, doubleTap: false, timestamp: 0 },
            down: { pressed: false, doubleTap: false, timestamp: 0 },
            right: { pressed: false, doubleTap: false, timestamp: 0 },
            space: { pressed: false, doubleTap: false, timestamp: 0 },
        };

        // Register event listeners for keydown and keyup events.
        window.addEventListener('keydown', (event) => this.keydownHandler(event));
        window.addEventListener('keyup', (event) => this.keyupHandler(event));
    }

    keydownHandler(event)
    {
        /** -- INSERT CODE HERE -- */
    }

    keyupHandler(event)
    {
        /** -- INSERT CODE HERE -- */
    }
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - 80;
    spineBoy.spine.scale.set(0.5);

    // Add character to the stage.
    app.stage.addChild(spineBoy.view);

    let currentAnimation;

    // Animate the character - just testing the controller at this point
    app.ticker.add((time) =>
    {
        const rightPressed = controller.keys.right.pressed;
        const animationName = rightPressed ? 'walk' : 'idle';
        const loop = true;

        // Apply the animation if it's different from the active one.
        if (currentAnimation !== animationName)
        {
            // Store the current animation name.
            currentAnimation = animationName;

            // Animate the character spine based on the right key state,
            spineBoy.spine.state.setAnimation(0, animationName, loop);
        }
    });
})();
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - 80;
    spineBoy.spine.scale.set(0.5);

    // Add character to the stage.
    app.stage.addChild(spineBoy.view);

    /** -- INSERT CODE HERE -- */
})();

Adding Keyboard Controller

Before we proceed to work on the character animations, we will need a handler for our keyboard input.

To speed things up, a Controller class has been set up on another file with the key map and the controller state map define, as well as the key listeners hooked up.

As you can we, we have 3 tracked properties on each of the state keys:

  • pressed simply tells whether the key is being pressed.
  • doubleTap tracks if the key has been rapidly pressed after letting go.
  • timestamp is an internal time tracker for determining whether the tap is considered as a double tap.

Please note that we have also defined W, A, S and D keys as directional input on the key map so they will behave like the arrow keys.

Let's start by updating our key-down and key-up handlers so that the controller state is updated accordingly.

Key-Down Handler

For this, we simply need to set the pressed state of the corresponded key state to true. And so for the doubleTap if the difference in time from the point of the timestamp recorded for that key is less than a threshold, 300ms in this case. Since the key-down handler will be called continuously while a key is held, the doubleTap state should remain true on subsequent callback if it was already, despite the growing deference in time from the timestamp (As the timestamp only gets reset on the key-up handler).

const key = keyMap[event.code];

if (!key) return;

const now = Date.now();

this.keys[key].pressed = true;
this.keys[key].doubleTap = this.keys[key].doubleTap || now - this.keys[key].timestamp < 300;

Key-Up Handler

Similary, we reset the pressed state of the corresponded key state to false on key-up, as well as the doubleTap state if it was previously true. Otherwise, we reset the timestamp to allow subsequent key presses to validate any rapid double-tap.

const key = keyMap[event.code];

if (!key) return;

const now = Date.now();

this.keys[key].pressed = false;

if (this.keys[key].doubleTap) this.keys[key].doubleTap = false;
else this.keys[key].timestamp = now;

Using Controller

Just like for our character, we then create an instance of the controller on the main index.js' IIFE.

const controller = new Controller();

Then we can try connecting the controller state to the character's walk animation. Let's do this for just the right key for now on an application's ticker update. Here, we temporarily store a reference to an active animation key on spot to only allow playing once per toggle since we are already specifying for them to be loops. The toggle will be between the animations with the key of idle and walk.

let currentAnimation;

app.ticker.add((time) =>
{
    const rightPressed = controller.keys.right.pressed;
    const animationName = rightPressed ? 'walk' : 'idle';
    const loop = true;

    if (currentAnimation !== animationName)
    {
        currentAnimation = animationName;
        spineBoy.spine.state.setAnimation(0, animationName, loop);
    }
});
import { Container } from 'pixi.js';
import { Spine } from '@esotericsoftware/spine-pixi-v8';

// Define the Spine animation map for the character.
// name: animation track key.
// loop: do the animation once or infinitely.
const animationMap = {
    idle: {
        name: 'idle',
        loop: true,
    },
    walk: {
        name: 'walk',
        loop: true,
    },
    run: {
        name: 'run',
        loop: true,
    },
    jump: {
        name: 'jump',
        timeScale: 1.5,
    },
    hover: {
        name: 'hoverboard',
        loop: true,
    },
    spawn: {
        name: 'portal',
    },
};

// Class for handling the character Spine and its animations.
export class SpineBoy
{
    constructor()
    {
        // The character's state.
        this.state = {
            walk: false,
            run: false,
            hover: false,
            jump: false,
        };

        // Create the main view and a nested view for directional scaling.
        this.view = new Container();
        this.directionalView = new Container();

        // Create the Spine instance using the preloaded Spine asset aliases.
        this.spine = Spine.from({
            skeleton: 'spineSkeleton',
            atlas: 'spineAtlas',
        });

        // Add the Spine instance to the directional view.
        this.directionalView.addChild(this.spine);

        // Add the directional view to the main view.
        this.view.addChild(this.directionalView);

        // Set the default mix duration for all animations.
        // This is the duration to blend from the previous animation to the next.
        this.spine.state.data.defaultMix = 0.2;
    }

    // Play the portal-in spawn animation.
    spawn()
    {
        this.spine.state.setAnimation(0, animationMap.spawn.name);
    }

    // Play the spine animation.
    playAnimation({ name, loop = false, timeScale = 1 })
    {
        // Skip if the animation is already playing.
        if (this.currentAnimationName === name) return;

        // Play the animation on main track instantly.
        const trackEntry = this.spine.state.setAnimation(0, name, loop);

        // Apply the animation's time scale (speed).
        trackEntry.timeScale = timeScale;
    }

    update()
    {
        // Play the jump animation if not already playing.
        if (this.state.jump) this.playAnimation(animationMap.jump);

        // Skip the rest of the animation updates during the jump animation.
        if (this.isAnimationPlaying(animationMap.jump)) return;

        // Handle the character animation based on the latest state and in the priority order.
        if (this.state.hover) this.playAnimation(animationMap.hover);
        else if (this.state.run) this.playAnimation(animationMap.run);
        else if (this.state.walk) this.playAnimation(animationMap.walk);
        else this.playAnimation(animationMap.idle);
    }

    isSpawning()
    {
        return this.isAnimationPlaying(animationMap.spawn);
    }

    isAnimationPlaying({ name })
    {
        // Check if the current animation on main track equals to the queried.
        // Also check if the animation is still ongoing.
        return this.currentAnimationName === name && !this.spine.state.getCurrent(0).isComplete();
    }

    // Return the name of the current animation on main track.
    get currentAnimationName()
    {
        return this.spine.state.getCurrent(0)?.animation.name;
    }

    // Return character's facing direction.
    get direction()
    {
        return this.directionalView.scale.x > 0 ? 1 : -1;
    }

    // Set character's facing direction.
    set direction(value)
    {
        this.directionalView.scale.x = value;
    }
}
import { Container } from 'pixi.js';
import { Spine } from '@esotericsoftware/spine-pixi-v8';

// Define the Spine animation map for the character.
// name: animation track key.
// loop: do the animation once or infinitely.
const animationMap = {
    idle: {
        name: 'idle',
        loop: true,
    },
    walk: {
        name: 'walk',
        loop: true,
    },
    run: {
        name: 'run',
        loop: true,
    },
    jump: {
        name: 'jump',
        timeScale: 1.5,
    },
    hover: {
        name: 'hoverboard',
        loop: true,
    },
    spawn: {
        name: 'portal',
    },
};

// Class for handling the character Spine and its animations.
export class SpineBoy
{
    constructor()
    {
        // The character's state.
        this.state = {
            walk: false,
            run: false,
            hover: false,
            jump: false,
        };

        // Create the main view and a nested view for directional scaling.
        this.view = new Container();
        this.directionalView = new Container();

        // Create the Spine instance using the preloaded Spine asset aliases.
        this.spine = Spine.from({
            skeleton: 'spineSkeleton',
            atlas: 'spineAtlas',
        });

        // Add the Spine instance to the directional view.
        this.directionalView.addChild(this.spine);

        // Add the directional view to the main view.
        this.view.addChild(this.directionalView);

        // Set the default mix duration for all animations.
        // This is the duration to blend from the previous animation to the next.
        this.spine.state.data.defaultMix = 0.2;
    }

    // Play the portal-in spawn animation.
    spawn()
    {
        this.spine.state.setAnimation(0, animationMap.spawn.name);
    }

    // Play the spine animation.
    playAnimation({ name, loop = false, timeScale = 1 })
    {
        // Skip if the animation is already playing.
        if (this.currentAnimationName === name) return;

        // Play the animation on main track instantly.
        const trackEntry = this.spine.state.setAnimation(0, name, loop);

        // Apply the animation's time scale (speed).
        trackEntry.timeScale = timeScale;
    }

    update()
    {
        /** -- INSERT CODE HERE -- */
    }

    isSpawning()
    {
        return this.isAnimationPlaying(animationMap.spawn);
    }

    isAnimationPlaying({ name })
    {
        // Check if the current animation on main track equals to the queried.
        // Also check if the animation is still ongoing.
        return this.currentAnimationName === name && !this.spine.state.getCurrent(0).isComplete();
    }

    // Return the name of the current animation on main track.
    get currentAnimationName()
    {
        return this.spine.state.getCurrent(0)?.animation.name;
    }

    // Return character's facing direction.
    get direction()
    {
        return this.directionalView.scale.x > 0 ? 1 : -1;
    }

    // Set character's facing direction.
    set direction(value)
    {
        this.directionalView.scale.x = value;
    }
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - 80;
    spineBoy.spine.scale.set(0.5);

    // Add character to the stage.
    app.stage.addChild(spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the character based on the controller's input.
    app.ticker.add(() =>
    {
        // Ignore the update loops while the character is doing the spawn animation.
        if (spineBoy.isSpawning()) return;

        // Update character's state based on the controller's input.
        spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
        if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
        else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
        spineBoy.state.hover = controller.keys.down.pressed;
        if (controller.keys.left.pressed) spineBoy.direction = -1;
        else if (controller.keys.right.pressed) spineBoy.direction = 1;
        spineBoy.state.jump = controller.keys.space.pressed;

        // Update character's animation based on the latest state.
        spineBoy.update();
    });
})();
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - 80;
    spineBoy.spine.scale.set(0.5);

    // Add character to the stage.
    app.stage.addChild(spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the character based on the controller's input.
    app.ticker.add(() =>
    {
        /** -- INSERT CODE HERE -- */
    });
})();

Animating Character

Returning to the star of our workshop, let's upgrade our Character to handle various movement animations. For this example, we will simply store a state set where we can then use an update loop to trigger animations according to the combination of the state values. We can then externally update the character state depending on the controller input state.

Preparation

For the upgrade, an animation map and assorted helper methods have been added to make handling Spine animation a little cleaner.

Animation Map

This lists out all the available animations to be included in our character, each with a name parameter that corresponds to an animation key existed on the character Spine data and an optional loop and timeScale parameters to customize the animation.

const animationMap = {
    idle: {
        name: 'idle',
        loop: true,
    },
    walk: {
        name: 'walk',
        loop: true,
    },
    run: {
        name: 'run',
        loop: true,
    },
    jump: {
        name: 'jump',
        timeScale: 1.5,
    },
    hover: {
        name: 'hoverboard',
        loop: true,
    },
    spawn: {
        name: 'portal',
    },
};

Helper Methods

playAnimation(animation)

Wraps Spine state's setAnimation(track, name, loop) method that plays an animation using a passed in animation data defined on the animation map. It prevents the same animation from being played on top of each other.


isAnimationPlaying(animation)

Check whether an animation is still active. That is when the Spine state's main track has a track entry of an animation with a key equals to that of the queried animation's name, and that the track entry is yet completed.


spawn()

Simply kick start the portal-in spawn animation. To be triggered externally.


isSpawning()

Utilizing the isAnimationPlaying(animation) to check if the spawn animation is still ongoing.


Handling Direction

You may have noticed that the spine instance is now wrapped in an extra directionalView container before being added to the main view. This is just to distinctly separate the transform, especially the horizontal scaling in this case where we will externally set to be 1 for rightward or -1 for leftward depending on the controller input state. A getter and setter for direction have been added for simplification.

Spine State Animation Default Mix

this.spine.state.data.defaultMix = 0.2 sets the default amount of time in second for the state to blend the animations when transitioning from one to another for all animations, like a cross-fade of the skeletal positions.

Update Loop

The only thing left to do is to handle the animation according to the character state in real-time on the update() method. Let's utilize all the stuff that has been prepared for us. In a logical order of priority for this specific example:

  • jump state should be handle immediately and the character should remain in the jump animation until it finishes even the jump state is no longer true.

  • The rest of the state members should trigger a corresponding animation immediately, depending on the priority order: hover > run > walk > idle. Note that multiple state members can be true at the same time, ie. walk will be true while run is true since the directional key is down in both scenarios.

if (this.state.jump) this.playAnimation(animationMap.jump);
if (this.isAnimationPlaying(animationMap.jump)) return;
if (this.state.hover) this.playAnimation(animationMap.hover);
else if (this.state.run) this.playAnimation(animationMap.run);
else if (this.state.walk) this.playAnimation(animationMap.walk);
else this.playAnimation(animationMap.idle);

Connecting to Controller

Back on index.js, let's trigger the character's spawn animation at the start and update our application's ticker update callback.

On the callback, we should skip updating the character state and calling its local update loop while the spawn animation is happening. Otherwise, we can hook the controller input state to the character state as followed:

  • left and right input pressed state will toggle on character's walk state and will update its direction value which should flip the character back and fourth horizontally to face the correct way. doubleTap state will also toggle on character's run state while still updating the direction accordingly.
  • down input state is dedicated to character's hover state.
  • space input state is dedicated to character's jump state.
spineBoy.spawn();

app.ticker.add(() =>
{
    if (spineBoy.isSpawning()) return;

    spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
    if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
    else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
    spineBoy.state.hover = controller.keys.down.pressed;
    if (controller.keys.left.pressed) spineBoy.direction = -1;
    else if (controller.keys.right.pressed) spineBoy.direction = 1;
    spineBoy.state.jump = controller.keys.space.pressed;

    spineBoy.update();
});
import { Container, Sprite, Texture, TilingSprite } from 'pixi.js';

// Class for handling the environment.
export class Scene
{
    constructor(width, height)
    {
        // Create a main view that holds all layers.
        this.view = new Container();

        // Create the stationary sky that fills the entire screen.
        this.sky = Sprite.from('sky');
        this.sky.anchor.set(0, 1);
        this.sky.width = width;
        this.sky.height = height;

        // Create textures for the background, mid-ground, and platform.
        const backgroundTexture = Texture.from('background');
        const midgroundTexture = Texture.from('midground');
        const platformTexture = Texture.from('platform');

        // Calculate the ideal platform height depending on the passed-in screen height.
        const maxPlatformHeight = platformTexture.height;
        const platformHeight = Math.min(maxPlatformHeight, height * 0.4);

        // Calculate the scale to be apply to all tiling textures for consistency.
        const scale = (this.scale = platformHeight / maxPlatformHeight);

        const baseOptions = {
            tileScale: { x: scale, y: scale },
            anchor: { x: 0, y: 1 },
            applyAnchorToTexture: true,
        };

        // Create the tiling sprite layers.
        this.background = new TilingSprite({
            texture: backgroundTexture,
            width,
            height: backgroundTexture.height * scale,
            ...baseOptions,
        });
        this.midground = new TilingSprite({
            texture: midgroundTexture,
            width,
            height: midgroundTexture.height * scale,
            ...baseOptions,
        });
        this.platform = new TilingSprite({
            texture: platformTexture,
            width,
            height: platformHeight,
            ...baseOptions,
        });

        // Calculate the floor height for external referencing.
        this.floorHeight = platformHeight * 0.43;

        // Position the backdrop layers.
        this.background.y = this.midground.y = -this.floorHeight;

        // Add all layers to the main view.
        this.view.addChild(this.sky, this.background, this.midground, this.platform);
    }
}
import { Container, Sprite, Texture, TilingSprite } from 'pixi.js';

// Class for handling the environment.
export class Scene
{
    constructor(width, height)
    {
        // Create a main view that holds all layers.
        this.view = new Container();

        /** -- INSERT CODE HERE -- */
    }
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { Scene } from './Scene';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create a scene that holds the environment.
    const scene = new Scene(app.screen.width, app.screen.height);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    scene.view.y = app.screen.height;
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - scene.floorHeight;
    spineBoy.spine.scale.set(scene.scale * 0.32);

    // Add scene and character to the stage.
    app.stage.addChild(scene.view, spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the character based on the controller's input.
    app.ticker.add(() =>
    {
        // Ignore the update loops while the character is doing the spawn animation.
        if (spineBoy.isSpawning()) return;

        // Update character's state based on the controller's input.
        spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
        if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
        else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
        spineBoy.state.hover = controller.keys.down.pressed;
        if (controller.keys.left.pressed) spineBoy.direction = -1;
        else if (controller.keys.right.pressed) spineBoy.direction = 1;
        spineBoy.state.jump = controller.keys.space.pressed;

        // Update character's animation based on the latest state.
        spineBoy.update();
    });
})();

Setting Up Scene

The scene is much less complicated and only involves a static Sprite for the sky and 3 TilingSprites for the parallax layers of the platform, the mid-ground and the background.

Again, a Scene class has been set up on another file with a view container added. And since we already preloaded all the required assets, we can go straight to the action.

We will establish the scene from bottom up so we are going to anchor all element at the bottom right corner.

Sky

Create the sky sprite, set the anchor as mentioned and use the passed in scene width and height as dimensions to fill up the whole scene.

this.sky = Sprite.from('sky');
this.sky.anchor.set(0, 1);
this.sky.width = width;
this.sky.height = height;

Parallax Layers

For the parallax layers, we begin by creating Textures from the preloaded assets.

const backgroundTexture = Texture.from('background');
const midgroundTexture = Texture.from('midground');
const platformTexture = Texture.from('platform');

We then calculate the ideal platform height which is 40% of the scene height but not exceeding the platform texture height. And then calculate a scale that we need to apply to the platform tiling texture to get it to the ideal height, which we also apply to other parallax layers for visual consistency.

const maxPlatformHeight = platformTexture.height;
const platformHeight = Math.min(maxPlatformHeight, height * 0.4);
const scale = this.scale = platformHeight / maxPlatformHeight;

Now we can create the TilingSprite objects from the defined textures and parameters.

const baseOptions = {
    tileScale: { x: scale, y: scale },
    anchor: { x: 0, y: 1 },
    applyAnchorToTexture: true,
};

this.background = new TilingSprite({
    texture: backgroundTexture,
    width,
    height: backgroundTexture.height * scale,
    ...baseOptions,
});
this.midground = new TilingSprite({
    texture: midgroundTexture,
    width,
    height: midgroundTexture.height * scale,
    ...baseOptions,
});
this.platform = new TilingSprite({
    texture: platformTexture,
    width,
    height: platformHeight,
    ...baseOptions,
});

After that, we need to horizontally offset the mid-ground and background layers to be just above the platform floor. Unfortunately, the platform tiling texture also includes the lamp element so we have to manually define the true height from the bottom of the platform to the floor surface. Let's store this as a member of the class, floorHeight, for external uses as well.

Then to wrap up the scene class, we just need to offset the mentioned layers up a floorHeight amount and add all layers to the main view.

this.floorHeight = platformHeight * 0.43;
this.background.y = this.midground.y = -this.floorHeight;
this.view.addChild(this.sky, this.background, this.midground, this.platform);

Adding the Scene

Note that index.js has already been updated to instantiate the scene and add it to the stage before the character.

const scene = new Scene(app.screen.width, app.screen.height);

app.stage.addChild(scene.view, spineBoy.view);

The scene is then placed at the bottom the screen and the character's transformation has been updated to take into account the platform floor height and the scene scaling.

scene.view.y = app.screen.height;
spineBoy.view.x = app.screen.width / 2;
spineBoy.view.y = app.screen.height - scene.floorHeight;
spineBoy.spine.scale.set(scene.scale * 0.32);


```javascript src/tutorials/v8.0.0/spineBoyAdventure/step6/Scene2-completed.js
import { Container, Sprite, Texture, TilingSprite } from 'pixi.js';

// Class for handling the environment.
export class Scene
{
    constructor(width, height)
    {
        // Create a main view that holds all layers.
        this.view = new Container();

        // Create the stationary sky that fills the entire screen.
        this.sky = Sprite.from('sky');
        this.sky.anchor.set(0, 1);
        this.sky.width = width;
        this.sky.height = height;

        // Create textures for the background, mid-ground, and platform.
        const backgroundTexture = Texture.from('background');
        const midgroundTexture = Texture.from('midground');
        const platformTexture = Texture.from('platform');

        // Calculate the ideal platform height depending on the passed-in screen height.
        const maxPlatformHeight = platformTexture.height;
        const platformHeight = Math.min(maxPlatformHeight, height * 0.4);

        // Calculate the scale to be apply to all tiling textures for consistency.
        const scale = (this.scale = platformHeight / maxPlatformHeight);

        const baseOptions = {
            tileScale: { x: scale, y: scale },
            anchor: { x: 0, y: 1 },
            applyAnchorToTexture: true,
        };

        // Create the tiling sprite layers.
        this.background = new TilingSprite({
            texture: backgroundTexture,
            width,
            height: backgroundTexture.height * scale,
            ...baseOptions,
        });
        this.midground = new TilingSprite({
            texture: midgroundTexture,
            width,
            height: midgroundTexture.height * scale,
            ...baseOptions,
        });
        this.platform = new TilingSprite({
            texture: platformTexture,
            width,
            height: platformHeight,
            ...baseOptions,
        });

        // Calculate the floor height for external referencing.
        this.floorHeight = platformHeight * 0.43;

        // Position the backdrop layers.
        this.background.y = this.midground.y = -this.floorHeight;

        // Add all layers to the main view.
        this.view.addChild(this.sky, this.background, this.midground, this.platform);
    }

    // Use the platform's horizontal position as the key position for the scene.
    get positionX()
    {
        return this.platform.tilePosition.x;
    }

    // Set the horizontal position of the platform layer while applying parallax scrolling to the backdrop layers.
    set positionX(value)
    {
        this.background.tilePosition.x = value * 0.1;
        this.midground.tilePosition.x = value * 0.25;
        this.platform.tilePosition.x = value;
    }
}
import { Container, Sprite, Texture, TilingSprite } from 'pixi.js';

// Class for handling the environment.
export class Scene
{
    constructor(width, height)
    {
        // Create a main view that holds all layers.
        this.view = new Container();

        // Create the stationary sky that fills the entire screen.
        this.sky = Sprite.from('sky');
        this.sky.anchor.set(0, 1);
        this.sky.width = width;
        this.sky.height = height;

        // Create textures for the background, mid-ground, and platform.
        const backgroundTexture = Texture.from('background');
        const midgroundTexture = Texture.from('midground');
        const platformTexture = Texture.from('platform');

        // Calculate the ideal platform height depending on the passed-in screen height.
        const maxPlatformHeight = platformTexture.height;
        const platformHeight = Math.min(maxPlatformHeight, height * 0.4);

        // Calculate the scale to be apply to all tiling textures for consistency.
        const scale = (this.scale = platformHeight / maxPlatformHeight);

        const baseOptions = {
            tileScale: { x: scale, y: scale },
            anchor: { x: 0, y: 1 },
            applyAnchorToTexture: true,
        };

        // Create the tiling sprite layers.
        this.background = new TilingSprite({
            texture: backgroundTexture,
            width,
            height: backgroundTexture.height * scale,
            ...baseOptions,
        });
        this.midground = new TilingSprite({
            texture: midgroundTexture,
            width,
            height: midgroundTexture.height * scale,
            ...baseOptions,
        });
        this.platform = new TilingSprite({
            texture: platformTexture,
            width,
            height: platformHeight,
            ...baseOptions,
        });

        // Calculate the floor height for external referencing.
        this.floorHeight = platformHeight * 0.43;

        // Position the backdrop layers.
        this.background.y = this.midground.y = -this.floorHeight;

        // Add all layers to the main view.
        this.view.addChild(this.sky, this.background, this.midground, this.platform);
    }

    // Use the platform's horizontal position as the key position for the scene.
    get positionX()
    {
        /** -- INSERT CODE HERE -- */
    }

    // Set the horizontal position of the platform layer while applying parallax scrolling to the backdrop layers.
    set positionX(value)
    {
        /** -- INSERT CODE HERE -- */
    }
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { Scene } from './Scene';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create a scene that holds the environment.
    const scene = new Scene(app.screen.width, app.screen.height);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    scene.view.y = app.screen.height;
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - scene.floorHeight;
    spineBoy.spine.scale.set(scene.scale * 0.32);

    // Add scene and character to the stage.
    app.stage.addChild(scene.view, spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the scene and the character based on the controller's input.
    app.ticker.add(() =>
    {
        // Ignore the update loops while the character is doing the spawn animation.
        if (spineBoy.isSpawning()) return;

        // Update character's state based on the controller's input.
        spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
        if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
        else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
        spineBoy.state.hover = controller.keys.down.pressed;
        if (controller.keys.left.pressed) spineBoy.direction = -1;
        else if (controller.keys.right.pressed) spineBoy.direction = 1;
        spineBoy.state.jump = controller.keys.space.pressed;

        // Update character's animation based on the latest state.
        spineBoy.update();

        // Determine the scene's horizontal scrolling speed based on the character's state.
        let speed = 1.25;

        if (spineBoy.state.hover) speed = 7.5;
        else if (spineBoy.state.run) speed = 3.75;

        // Shift the scene's position based on the character's facing direction, if in a movement state.
        if (spineBoy.state.walk) scene.positionX -= speed * scene.scale * spineBoy.direction;
    });
})();
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { Scene } from './Scene';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create a scene that holds the environment.
    const scene = new Scene(app.screen.width, app.screen.height);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    scene.view.y = app.screen.height;
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - scene.floorHeight;
    spineBoy.spine.scale.set(scene.scale * 0.32);

    // Add scene and character to the stage.
    app.stage.addChild(scene.view, spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the scene and the character based on the controller's input.
    app.ticker.add(() =>
    {
        // Ignore the update loops while the character is doing the spawn animation.
        if (spineBoy.isSpawning()) return;

        // Update character's state based on the controller's input.
        spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
        if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
        else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
        spineBoy.state.hover = controller.keys.down.pressed;
        if (controller.keys.left.pressed) spineBoy.direction = -1;
        else if (controller.keys.right.pressed) spineBoy.direction = 1;
        spineBoy.state.jump = controller.keys.space.pressed;

        // Update character's animation based on the latest state.
        spineBoy.update();

        /** -- INSERT CODE HERE -- */
    });
})();

Animating Scene

Last but not least, we need to match the Scene scroll according to the character movement state.

Lets begin by having an unified positionX property for the Scene class. For the getter, this will simply return the tilePosition.x of the platform TilingSprite, and similarly for the setter we set its tilePosition.x directly but also so set tilePosition.x of the mid-ground and the background TilingSprites at descending fractions of the value. This is to create a parallax scrolling effect for the backdrop layers as the platform horizontal position changes.

Getter

return this.platform.tilePosition.x;

Setter

this.background.tilePosition.x = value * 0.1;
this.midground.tilePosition.x = value * 0.25;
this.platform.tilePosition.x = value;

Then on the main index.js, let's manipulate this positionX property at the end of the application's ticker callback to animate the scrolling accordingly. Here, we will use 3 different scrolling speeds for character's walk, run and hover state. We need to also add to or subtract from the property depending on the direction/

let speed = 1.25;

if (spineBoy.state.hover) speed = 7.5;
else if (spineBoy.state.run) speed = 3.75;

if (spineBoy.state.walk)
{
    scene.positionX -= speed * scene.scale * spineBoy.direction;
}
import { Application, Assets } from 'pixi.js';
import '@esotericsoftware/spine-pixi-v8';
import { Controller } from './Controller';
import { Scene } from './Scene';
import { SpineBoy } from './SpineBoy';

// Asynchronous IIFE
(async () =>
{
    // Create a PixiJS application.
    const app = new Application();

    // Intialize the application.
    await app.init({ background: '#1099bb', resizeTo: window });

    // Then adding the application's canvas to the DOM body.
    document.body.appendChild(app.canvas);

    // Load the assets.
    await Assets.load([
        {
            alias: 'spineSkeleton',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pro.skel',
        },
        {
            alias: 'spineAtlas',
            src: 'https://raw.githubusercontent.com/pixijs/spine-v8/main/examples/assets/spineboy-pma.atlas',
        },
        {
            alias: 'sky',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/sky.png',
        },
        {
            alias: 'background',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/background.png',
        },
        {
            alias: 'midground',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/midground.png',
        },
        {
            alias: 'platform',
            src: 'https://pixijs.com/assets/tutorials/spineboy-adventure/platform.png',
        },
    ]);

    // Create a controller that handles keyboard inputs.
    const controller = new Controller();

    // Create a scene that holds the environment.
    const scene = new Scene(app.screen.width, app.screen.height);

    // Create our character
    const spineBoy = new SpineBoy();

    // Adjust views' transformation.
    scene.view.y = app.screen.height;
    spineBoy.view.x = app.screen.width / 2;
    spineBoy.view.y = app.screen.height - scene.floorHeight;
    spineBoy.spine.scale.set(scene.scale * 0.32);

    // Add scene and character to the stage.
    app.stage.addChild(scene.view, spineBoy.view);

    // Trigger character's spawn animation.
    spineBoy.spawn();

    // Animate the scene and the character based on the controller's input.
    app.ticker.add(() =>
    {
        // Ignore the update loops while the character is doing the spawn animation.
        if (spineBoy.isSpawning()) return;

        // Update character's state based on the controller's input.
        spineBoy.state.walk = controller.keys.left.pressed || controller.keys.right.pressed;
        if (spineBoy.state.run && spineBoy.state.walk) spineBoy.state.run = true;
        else spineBoy.state.run = controller.keys.left.doubleTap || controller.keys.right.doubleTap;
        spineBoy.state.hover = controller.keys.down.pressed;
        if (controller.keys.left.pressed) spineBoy.direction = -1;
        else if (controller.keys.right.pressed) spineBoy.direction = 1;
        spineBoy.state.jump = controller.keys.space.pressed;

        // Update character's animation based on the latest state.
        spineBoy.update();

        // Determine the scene's horizontal scrolling speed based on the character's state.
        let speed = 1.25;

        if (spineBoy.state.hover) speed = 7.5;
        else if (spineBoy.state.run) speed = 3.75;

        // Shift the scene's position based on the character's facing direction, if in a movement state.
        if (spineBoy.state.walk) scene.positionX -= speed * scene.scale * spineBoy.direction;
    });
})();

You did it!

Congratulations, we hope the adventure was worthwhile! There is so much more Spine and the Pixi Spine plugin can do so please feel free to check out Esoteric's official Spine runtime API documentation and explore our Pixi Spine examples.

PixiJS Userland Projects

PixiJS Userland Projects

A curated list of active community plugins and tools that extend PixiJS. These are maintained under the pixijs-userland GitHub organization.


PIXI.TextStyle Generator A tool for configuring text styles in PixiJS.


Rectangular tilemap implementation for PixiJS Highly optimized tile rendering via WebGL and Canvas.


Pixi.js plugin for Spine animation Official support for integrating Spine skeleton animations in PixiJS projects.


3D-like perspective rendering Enable 2.5D projection effects in your PixiJS scenes.


Configurable 2D camera and panning/zooming viewport Touch and mouse support built-in. Useful for large or zoomable scenes.


Adobe Animate CC extension for PixiJS export Exports content from Animate to run in PixiJS.


PIXI-based particle system editor Design particle effects in a visual editor.


Flexible and fast particle system for PixiJS Includes gravity, alpha, scale, and animation controls.


Anti-aliased replacement for PIXI.Graphics Improves the visual quality of drawn shapes.


Advanced color modes and lighting for PixiJS Supports sprites, meshes, and color transformations.


Z-order layering plugin Manages display object layering independently of display hierarchy.


Dynamic lighting via deferred shading Bring per-pixel lights and shadows to your PixiJS scenes.


Tiled map loader Load .tmx maps from Tiled into PixiJS.


Display object for marquee UI selection Enables rectangular selection dragging, similar to RTS games or UI editors.


Color filters and presets A collection of ready-to-use color manipulation filters.


Organization website GitHub Pages site for the PixiJS Userland project list and documentation.


LDtk level loader Load levels created in LDtk for use with PixiJS.


Improved sprite renderer with anti-aliasing and blend modes Helps reduce edge artifacts and adds 3 custom blend modes.


Run PixiJS in Node.js (no browser) Enables Pixi rendering in headless or server-side contexts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment