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:
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
.
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.
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.
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.
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.
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
.
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);
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.
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.
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!
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 ;)
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.
Right here! Take a look through the Resources section for a wealth of information including documentation, forums, tutorials and the Goodboy blog.
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.
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!
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.
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.
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.
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.
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.
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. |
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.
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.
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.
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.
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.
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.
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'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!)
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.
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.
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
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.
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.
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.
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.
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 |
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.
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
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 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.
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.
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 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.
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.
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.
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.
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
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.
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')
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.
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.
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:
- Show a loading image
- Use Assets to ensure that all textures are loaded
- optionally update your loading image based on progress callbacks
- On loader completion, run all objects and use
Texture.from()
to pull the loaded textures out of the texture cache - Prepare your textures (optional - see below)
- 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.
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.
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.
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.
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.
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.
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);
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.
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.
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.
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
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.
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.
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!
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!
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.
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.
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.
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.
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'
}
})
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.
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.
- 3rd party solutions
- BitmapFont.from auto-generation
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 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.
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.
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>
`);
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
.
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.
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.
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.
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!
:::
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
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
// 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);
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
});
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);
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!
});
- 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'
});
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
});
- 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);
- Power of Two Textures: Textures should be power-of-two dimensions for proper tiling in WebGL1 (WebGL2 and WebGPU are fine).
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 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);
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), where0
represents the left/top edge and1
represents the right/bottom edge of the shape. -
end {x, y}
: These define the ending point of the gradient. Similar tostart {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' },
],
});
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);
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), where0.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. Likecenter {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);
-
Memory Management: Use
fillGradient.destroy()
to free up resources when gradients are no longer needed. -
Animation: Update existing gradients instead of creating new ones for better performance.
-
Custom Shaders: For complex animations, custom shaders may be more efficient.
-
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.
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,
});
const obj = new Graphics().rect(0, 0, 100, 100)
.fill({
texture: texture,
color: 'yellow',
alpha: 0.5,
});
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!
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.
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. |
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. |
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.
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
}
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.
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 Container
s 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,
}
});
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.
:::
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);
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.
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.
- 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.
- 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.
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.
- 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.
- 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 useupdateCacheTexture
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.
-
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 applycacheAsTexture
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!
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:
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.
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.
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.
- 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.
- 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
andantialias: 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
- 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 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)
- 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
- 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 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!
- 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!
- 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
- 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
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);
})();
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.
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;
})();
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;
});
})();
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;
});
})();
Congratulations! Now you are ready for the real world ~
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);
})();
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.
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);
})();
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);
})();
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);
})();
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.
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;
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.
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);
})();
Let's apply the same principles we used on the mountains step and do the same thing for the trees layer.
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;
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);
}
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);
})();
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.
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);
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;
}
});
});
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);
})();
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.
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 });
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;
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);
})();
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;
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);
})();
For the final touch, let's create groups of smoke particles animating in from the train chimney and out off the screen.
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);
}
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);
})();
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.
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 -- */
}
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.
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);
}
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);
})();
Now lets fill the pond with some rocks and pebbles, shall we? Let's work inside the already prepared addBackground
function.
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);
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));
})();
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.
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);
}
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);
});
})();
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.
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);
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);
});
})();
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);
});
})();
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',
},
]);
})();
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.
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.
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);
Let's then preload all of our required assets upfront which includes:
- Spine Assets
- Skeleton data file.
- Accompanying ATLAS.
- 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 -- */
})();
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 -- */
})();
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.
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;
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;
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 -- */
});
})();
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.
For the upgrade, an animation map and assorted helper methods have been added to make handling Spine animation a little cleaner.
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',
},
};
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.
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.
Simply kick start the portal-in spawn animation. To be triggered externally.
Utilizing the isAnimationPlaying(animation)
to check if the spawn animation is still ongoing.
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.
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.
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 longertrue
. -
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 betrue
at the same time, ie.walk
will betrue
whilerun
istrue
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);
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
andright
inputpressed
state will toggle on character'swalk
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'srun
state while still updating the direction accordingly.down
input state is dedicated to character'shover
state.space
input state is dedicated to character'sjump
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();
});
})();
The scene is much less complicated and only involves a static Sprite
for the sky and 3 TilingSprite
s 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.
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;
For the parallax layers, we begin by creating Texture
s 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);
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 -- */
});
})();
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 TilingSprite
s at descending fractions of the value. This is to create a parallax scrolling effect for the backdrop layers as the platform horizontal position changes.
return this.platform.tilePosition.x;
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;
});
})();
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.
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.
The accessibility module provides screen reader and keyboard navigation support for PixiJS content. This is very important as it can possibly help people with disabilities access PixiJS content.
This module is a mixin for AbstractRenderer and needs to be imported if managing your own renderer:
import 'pixi.js/accessibility';
Make objects accessible by setting their properties:
container.accessible = true; // Enable accessibility for this container
container.accessibleType = 'button'// Type of DOM element to create (default: 'button')
container.accessibleTitle = 'Play'// Optional: Add screen reader labels
By default, the accessibility system activates when users press the tab key. For cases where you need control over when accessibility features are active, configuration options are available:
const app = new Application({
accessibilityOptions: {
enabledByDefault: true, // Create accessibility elements immediatelyactivateOnTab: false, // Prevent tab key activationdebug: false, // Show accessibility divsdeactivateOnMouseMove: false, // Prevent accessibility from being deactivated when mouse moves
}
});
The system can also be controlled programmatically:
app.renderer.accessibility.setAccessibilityEnabled(true);
See AccessibleOptions for all configuration options.
When accessible
is enabled on any display object, these properties will affect its accessibility.
Name | Type | Default | Description |
---|---|---|---|
accessible | boolean | false | Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set |
accessibleChildren | boolean | true | Setting to false will prevent any children inside this container to be accessible. Defaults to true. |
accessibleHint | string | null | Sets the aria-label attribute of the shadow div | |
accessibleText | string | null | Sets the text content of the shadow div | |
accessibleTitle | string | Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]' | |
accessibleType | keyof | 'button' | Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button. |
tabIndex | number | 0 |
See accessibility_accessibilityTarget.ts.html:3
The type of the pointer event to listen for. Can be any of the following:
auto
none
visiblePainted
visibleFill
visibleStroke
visible
painted
fill
stroke
all
inherit
See: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
The Accessibility system provides screen reader and keyboard navigation support for PixiJS content. It creates an accessible DOM layer over the canvas that can be controlled programmatically or through user interaction.
By default, the system activates when users press the tab key. This behavior can be customized through options:
const app = new Application({
accessibilityOptions: {
enabledByDefault: true, // Enable immediately instead of waiting for tabactivateOnTab: false, // Disable tab key activationdebug: false, // Show/hide accessibility divsdeactivateOnMouseMove: false, // Prevent accessibility from being deactivated when mouse moves
}
});
The system can also be controlled programmatically:
app.renderer.accessibility.setAccessibilityEnabled(true);
To make individual containers accessible:
container.accessible = true;
An instance of this class is automatically created at renderer.accessibility
See accessibility_AccessibilitySystem.ts.html:190
Name | Type | Description |
---|---|---|
renderer | WebGLRenderer | WebGPURenderer | A reference to the current renderer |
default options used by the system
Name | Type | Default | Description |
---|---|---|---|
activateOnTab | boolean | true | Whether to activate accessibility when tab key is pressed |
deactivateOnMouseMove | boolean | true | Whether to deactivate accessibility when mouse moves |
debug | boolean | false | Whether to visually show the accessibility divs for debugging |
enabledByDefault | boolean | false | Whether to enable accessibility features on initialization |
Whether accessibility divs are visible for debugging
Default Value:
: - false
Value of true
if accessibility is currently active and accessibility layers are showing.
Value of true
if accessibility is enabled for touch devices.
See accessibility_AccessibilitySystem.ts.html:828
Destroys the accessibility system. Removes all elements and listeners.
See accessibility_AccessibilitySystem.ts.html:845
Enables or disables the accessibility system.
Name | Type | Description |
---|---|---|
enabled | boolean | Whether to enable or disable accessibility. |
When accessible
is enabled on any display object, these properties will affect its accessibility.
Name | Type | Default | Description |
---|---|---|---|
accessible | boolean | false | Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set |
accessibleChildren | boolean | true | Setting to false will prevent any children inside this container to be accessible. Defaults to true. |
accessibleHint | string | null | Sets the aria-label attribute of the shadow div | |
accessibleText | string | null | Sets the text content of the shadow div | |
accessibleTitle | string | Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]' | |
accessibleType | keyof | 'button' | Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button. |
tabIndex | number | 0 |
Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set
Default Value:
: - false
Setting to false will prevent any children inside this container to be accessible. Defaults to true.
Default Value:
: - true
Sets the aria-label attribute of the shadow div
Sets the text content of the shadow div
Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]'
Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button.
Default Value:
: - 'button'
Default Value:
: - 0
The app module provides a set of classes to use as a starting point when building applications.
This module has a mixin for TickerPlugin
and ResizePlugin
. These will need to be imported if you are managing your own renderer.
import { Application } from'pixi.js';
const app = new Application();
await app.init();
// don't forget to add the canvas to the DOMdocument.body.appendChild(app.canvas);
Application options supplied to the init method.
Name | Type | Default | Description |
---|---|---|---|
autoStart | boolean | true | Automatically starts the rendering after the construction. Note: Setting this parameter to false does NOT stop the shared ticker even if you set options.sharedTicker to true in case that it is already started. Stop it by your own. |
resizeTo | Window | HTMLElement | Element to automatically resize the renderer to. | |
sharedTicker | boolean | false | Settrue to use Ticker.shared , false to create new ticker. If set to false , you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker. |
import { Application } from 'pixi.js';
const app = new Application();
await app.init({
autoStart: false,
resizeTo: window,
sharedTicker: true,
});
Application options for the ResizePlugin.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
resizeTo | Window | HTMLElement | <optional> | window | Element to automatically resize the renderer to. |
Application options for the TickerPlugin.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
autoStart | boolean | <optional> | true | Automatically starts the rendering after the construction. Note: Setting this parameter to false does NOT stop the shared ticker even if you set options.sharedTicker to true in case that it is already started. Stop it by your own. |
sharedTicker | boolean | <optional> | false | Settrue to use Ticker.shared , false to create new ticker. If set to false , you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker. |
Convenience class to create a new PixiJS application.
This class automatically creates the renderer, ticker and root container.
See app_Application.ts.html:118
Create new Application instance
import { Application, Sprite } from 'pixi.js';
// Create the application
const app = new Application();
await app.init({ width: 800, height: 600 });
// Add the view to the DOM
document.body.appendChild(app.canvas);
// ex, add display objects
app.stage.addChild(Sprite.from('something.png'));
Collection of installed plugins.
Reference to the renderer's canvas element.
rendererRenderer
WebGL renderer if available, otherwise CanvasRenderer.
The HTML element or window to automatically resize the renderer's view element to match width and height.
screenRectanglereadonly
Reference to the renderer's screen rectangle. Its safe to use as filterArea
or hitArea
for the whole screen.
stageContainer
The root display container that's rendered.
tickerTicker
Ticker for doing render updates.
Default Value:
: - Ticker.shared
Reference to the renderer's canvas element.
See app_Application.ts.html:191
Destroys the application and all of its resources.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
rendererDestroyOptions | object | boolean | <optional> | false | The options for destroying the renderer. |
rendererDestroyOptions.removeView | boolean | <optional> | false | Removes the Canvas element from the DOM. |
options | object | boolean | <optional> | false | The options for destroying the stage. |
options.children | boolean | <optional> | false | If set to true, all the children will have their destroy method called as well. options will be passed on to those calls. |
options.texture | boolean | <optional> | false | Only used for children with textures e.g. Sprites. If options.children is set to true, it should destroy the texture of the child sprite. |
options.textureSource | boolean | <optional> | false | Only used for children with textures e.g. Sprites. If options.children is set to true, it should destroy the texture source of the child sprite. |
options.context | boolean | <optional> | false | Only used for children with graphicsContexts e.g. Graphics. If options.children is set to true, it should destroy the context of the child graphics. |
See app_Application.ts.html:135
Name | Type | Attributes | Description |
---|---|---|---|
options | Partial<ApplicationOptions> | <optional> | The optional application and renderer parameters. |
See app_Application.ts.html:152
Render the current stage.
See app_ResizePlugin.ts.html:118
Execute an immediate resize on the renderer, this is not throttled and can be expensive to call many times in a row. Will resize only if resizeTo
property is set.
See app_TickerPlugin.ts.html:106
Convenience method for starting the render.
See app_TickerPlugin.ts.html:95
Convenience method for stopping the render.
Calls global PIXI_APP_INIT hook with the application instance, after the application is initialized.
Application options supplied to the init method.
Name | Type | Default | Description |
---|---|---|---|
autoStart | boolean | true | Automatically starts the rendering after the construction. Note: Setting this parameter to false does NOT stop the shared ticker even if you set options.sharedTicker to true in case that it is already started. Stop it by your own. |
resizeTo | Window | HTMLElement | Element to automatically resize the renderer to. | |
sharedTicker | boolean | false | Settrue to use Ticker.shared , false to create new ticker. If set to false , you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker. |
import { Application } from 'pixi.js';
const app = new Application();
await app.init({
autoStart: false,
resizeTo: window,
sharedTicker: true,
});
- AutoDetectOptions
- PixiMixins.ApplicationOptions
Automatically starts the rendering after the construction. Note: Setting this parameter to false
does NOT stop the shared ticker even if you set options.sharedTicker
to true
in case that it is already started. Stop it by your own.
Default Value:
: - true
Element to automatically resize the renderer to.
Settrue
to use Ticker.shared
, false
to create new ticker. If set to false
, you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker.
Default Value:
: - false
An Application plugin that will automatically cull your stage using the renderers screen size.
See: Culler
import { extensions, CullerPlugin } from 'pixi.js';
extensions.add(CullerPlugin);
Middleware for Application's resize functionality.
Adds the following methods to Application:
Middleware for Application's resize functionality.
import { extensions, ResizePlugin } from 'pixi.js';
extensions.add(ResizePlugin);
Application options for the ResizePlugin.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
resizeTo | Window | HTMLElement | <optional> | window | Element to automatically resize the renderer to. |
Element to automatically resize the renderer to.
Default Value:
: - window
Middleware for Application's Ticker functionality.
Adds the following methods to Application:
Middleware for Application's Ticker functionality.
import { extensions, TickerPlugin } from 'pixi.js';
extensions.add(TickerPlugin);
Application options for the TickerPlugin.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
autoStart | boolean | <optional> | true | Automatically starts the rendering after the construction. Note: Setting this parameter to false does NOT stop the shared ticker even if you set options.sharedTicker to true in case that it is already started. Stop it by your own. |
sharedTicker | boolean | <optional> | false | Settrue to use Ticker.shared , false to create new ticker. If set to false , you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker. |
Automatically starts the rendering after the construction. Note: Setting this parameter to false
does NOT stop the shared ticker even if you set options.sharedTicker
to true
in case that it is already started. Stop it by your own.
Default Value:
: - true
Settrue
to use Ticker.shared
, false
to create new ticker. If set to false
, you cannot register a handler to occur before anything that runs on the shared ticker. The system ticker will always run before both the shared ticker and the app ticker.
Default Value:
: - false
A one stop shop for all Pixi resource management! Super modern and easy to use, with enough flexibility to customize and do what you need!
Use the singleton class Assets to easily load and manage all your assets.
import { Assets, Texture } from'pixi.js';
const bunnyTexture = await Assets.load<Texture>('bunny.png');
const sprite = new Sprite(bunnyTexture);
Check out the sections below for more information on how to deal with assets.
Asset Loading
Do not be afraid to load things multiple times - under the hood, it will NEVER load anything more than once.
For example:
import { Assets } from'pixi.js';
promise1 = Assets.load('bunny.png')
promise2 = Assets.load('bunny.png')
// promise1 === promise2
Here both promises will be the same. Once resolved... Forever resolved! It makes for really easy resource management!
Out of the box Pixi supports the following files:
- Textures (avif, webp, png, jpg, gif, svg) via loadTextures, loadSvg
- Video Textures (mp4, m4v, webm, ogg, ogv, h264, avi, mov) via loadVideoTextures
- Sprite sheets (json) via spritesheetAsset
- Bitmap fonts (xml, fnt, txt) via assets.loadBitmapFont
- Web fonts (ttf, woff, woff2) via loadWebFont
- JSON files (json) via loadJson
- Text Files (txt) via loadTxt More types can be added fairly easily by creating additional LoaderParsers.
Textures
- Textures are loaded as ImageBitmap on a worker thread where possible. Leading to much less janky load + parse times.
- By default, we will prefer to load AVIF and WebP image files if you specify them. But if the browser doesn't support AVIF or WebP we will fall back to png and jpg.
- Textures can also be accessed via
Texture.from()
(see Texture.from) and now use this asset manager under the hood! - Don't worry if you set preferences for textures that don't exist (for example you prefer 2x resolutions images but only 1x is available for that texture, the Assets manager will pick that up as a fallback automatically)
- It's hard to know what resolution a sprite sheet is without loading it first, to address this there is a naming convention we have added that will let Pixi understand the image format and resolution of the spritesheet via its file name:
my-spritesheet{resolution}.{imageFormat}.json
For example:[email protected]
* // 2x resolution, WebP sprite sheet*[email protected]
* // 0.5x resolution, png sprite sheet*
- This is optional! You can just load a sprite sheet as normal. This is only useful if you have a bunch of different res / formatted spritesheets.
Fonts
Web fonts will be loaded with all weights. It is possible to load only specific weights by doing the following:
import { Assets } from'pixi.js';
// Load specific weights..await Assets.load({
data: {
weights: ['normal'], // Only loads the weight
},
src: `outfit.woff2`,
});
// Load everything...await Assets.load(`outfit.woff2`);
Background Loading
Background loading will load stuff for you passively behind the scenes. To minimize jank, it will only load one asset at a time. As soon as a developer calls Assets.load(...)
the background loader is paused and requested assets are loaded as a priority. Don't worry if something is in there that's already loaded, it will just get skipped!
You still need to call Assets.load(...)
to get an asset that has been loaded in the background. It's just that this promise will resolve instantly if the asset has already been loaded.
Manifest and Bundles
- Manifest is a descriptor that contains a list of all assets and their properties.
- Bundles are a way to group assets together.
import { Assets } from'pixi.js';
// Manifest Exampleconst manifest = {
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',
},
],
},
]
};
await Assets.init({ manifest });
// Load a bundle...
loadScreenAssets = await Assets.loadBundle('load-screen');
// Load another bundle...
gameScreenAssets = await Assets.loadBundle('game-screen');
This developer convenience object allows developers to group together the various asset parsers into a single object.
import { AssetExtension, extensions } from 'pixi.js';
// create the CacheParser
const cache = {
test(asset: item): boolean {
// Gets called by the cache when a dev caches an asset
},
getCacheableAssets(keys: string[], asset: item): Record<string, any> {
// If the test passes, this function is called to get the cacheable assets
// an example may be that a spritesheet object will return all the sub textures it has so they can
// be cached.
},
};
// create the ResolveURLParser
const resolver = {
test(value: string): boolean {
// the test to perform on the url to determine if it should be parsed
},
parse(value: string): ResolvedAsset {
// the function that will convert the url into an object
},
};
// create the LoaderParser
const loader = {
name: 'itemLoader',
extension: {
type: ExtensionType.LoadParser,
},
async testParse(asset: any, options: ResolvedAsset) {
// This function is used to test if the parse function should be run on the asset
},
async parse(asset: any, options: ResolvedAsset, loader: Loader) {
// Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
},
unload(item: any) {
// If an asset is parsed using this parser, the unload function will be called when the user requests an asset
// to be unloaded. This is useful for things like sounds or textures that can be unloaded from memory
},
};
// put it all together and create the AssetExtension
extensions.add({
extension: ExtensionType.Asset,
cache,
resolver,
loader,
}
A more verbose version of the AssetExtension, allowing you to set the cached, loaded, parsed, and unloaded asset separately
Name | Type | Description |
---|---|---|
cache | Partial<CACHE_ASSET<CacheParser>> | the asset cache parser |
detection | Partial<FormatDetectionParser> | the asset format detection parser |
extension | Asset | The type of extension |
loader | LoaderParserAdvanced<META_DATA, ASSET, PARSED_ASSET, UNLOAD_ASSET> | the asset loader |
resolver | Partial<ResolveURLParser> | the asset resolve parser |
Initialization options object for the Assets Class.
Name | Type | Description |
---|---|---|
basePath | string | a base path for any assets loaded |
bundleIdentifier | BundleIdentifierOptions | advanced - override how bundlesIds are generated |
defaultSearchParams | string | Record<string, any> | a default URL parameter string to append to all assets loaded |
manifest | string | AssetsManifest | a manifest to tell the asset loader upfront what all your assets are this can be the manifest object itself, or a URL to the manifest. |
preferences | Partial<AssetsPreferences> | Optional loader preferences |
skipDetections | boolean | If true, don't attempt to detect whether browser has preferred formats available. May result in increased performance as it skips detection step. |
texturePreference | { resolution?: number | number[], format?: ArrayOr<string>} | optional preferences for which textures preferences you have when resolving assets for example you might set the resolution to 0.5 if the user is on a rubbish old phone or you might set the resolution to 2 if the user is on a retina display |
Structure of a bundle found in a Manifest file
Name | Type | Description |
---|---|---|
assets | UnresolvedAsset[] | UnresolvedAsset<string, ArrayOr<string> | Record> | The assets in the bundle |
name | string | The name of the bundle |
The expected format of a manifest. This could be auto generated or hand made
Name | Type | Description |
---|---|---|
bundles | AssetsBundle[] | array of bundles |
Extensible preferences that can be used, for instance, when configuring loaders.
Since:
: - 7.2.0
Options for how the resolver deals with generating bundle ids
Name | Type | Description |
---|---|---|
connector | string | The character that is used to connect the bundleId and the assetId when generating a bundle asset id key |
createBundleAssetId | (bundleId: string, assetId: string) => string | A function that generates a bundle asset id key from a bundleId and an assetId |
extractAssetIdFromBundle | (bundleId: string, assetBundleId: string) => string | A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId |
For every asset that is cached, it will call the parsers test function the flow is as follows:
cacheParser.test()
: Test the asset.cacheParser.getCacheableAssets()
: If the test passes call the getCacheableAssets function with the asset
Useful if you want to add more than just a raw asset to the cache (for example a spritesheet will want to make all its sub textures easily accessible in the cache)
Name | Type | Description |
---|---|---|
config | Record<string, any> | A config to adjust the parser |
extension | ExtensionMetadata | The extension type of this cache parser |
getCacheableAssets | (keys: string[], asset: T) => Record<string, any> | If the test passes, this function is called to get the cacheable assets an example may be that a spritesheet object will return all the sub textures it has so they can be cached. |
test | (asset: T) => boolean | Gets called by the cache when a dev caches an asset |
Format detection is useful for detecting feature support on the current platform.
Name | Type | Description |
---|---|---|
add | (formats: string[]) => Promise<string[]> | Add formats (file extensions) to the existing list of formats. Return an new array with added formats, do not mutate the formats argument. |
extension | ExtensionMetadata | Should be ExtensionType.DetectionParser |
remove | (formats: string[]) => Promise<string[]> | Remove formats (file extensions) from the list of supported formats. This is used when uninstalling this DetectionParser. Return an new array with filtered formats, do not mutate the formats argument. |
test | () => Promise<boolean> | Browser/platform feature detection supported if return true |
The interface to define a loader parser (all functions are optional).
When you create a parser
object, the flow for every asset loaded is:
parser.test()
- Each URL to load will be tested here, if the test is passed the assets are loaded using the load function below. Good place to test for things like file extensions!parser.load()
- This is the promise that loads the URL provided resolves with a loaded asset if returned by the parser.parser.testParse()
- This function is used to test if the parse function should be run on the asset If this returns true then parse is called with the assetparse.parse()
- Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
Some loaders may only be used for parsing, some only for loading, and some for both!
Configuration for the loadSVG plugin.
Name | Type | Default | Description |
---|---|---|---|
crossOrigin | HTMLImageElement["crossOrigin"] | 'anonymous' | The crossOrigin value to use for loading the SVG as an image. |
parseAsGraphicsContext | boolean | false | When set to true , loading and decoding images will happen with new Image() , |
See: assets.loadSVG
Configuration for the loadTextures plugin.
Name | Type | Default | Description |
---|---|---|---|
crossOrigin | HTMLImageElement["crossOrigin"] | 'anonymous' | The crossOrigin value to use for images when preferCreateImageBitmap is false . |
preferCreateImageBitmap | boolean | true | When set to true , loading and decoding images will happen with createImageBitmap , otherwise it will use new Image() . |
preferWorkers | boolean | true | When set to true , loading and decoding images will happen with Worker thread, if available on the browser. This is much more performant as network requests and decoding can be expensive on the CPU. However, not all environments support Workers, in some cases it can be helpful to disable by setting to false . |
See: loadTextures
A prefer order lets the resolver know which assets to prefer depending on the various parameters passed to it.
Name | Type | Description |
---|---|---|
priority | string[] | the importance order of the params |
A promise and parser pair
Name | Type | Description |
---|---|---|
parser | LoaderParser | the parser that is loading the asset |
promise | Promise<any> | the promise that is loading the asset |
A fully resolved asset, with all the information needed to load it.
Name | Type | Description |
---|---|---|
alias | string[] | Aliases associated with asset |
data | T | Optional data |
format | string | Format, usually the file extension |
loadParser | LoadParserName | An override that will ensure that the asset is loaded with a specific parser |
src | string | The URL or relative path to the asset |
Format for url parser, will test a string and if it pass will then parse it, turning it into an ResolvedAsset
Name | Type | Description |
---|---|---|
config | Record<string, any> | A config to adjust the parser |
parse | (value: string) => ResolvedAsset & { [key: string]: any } | the function that will convert the url into an object |
test | (url: string) => boolean | the test to perform on the url to determine if it should be parsed |
Atlas format.
Name | Type | Description |
---|---|---|
animations | Dict<string[]> | The animations of the atlas. |
frames | Dict<SpritesheetFrameData> | The frames of the atlas. |
meta | { app?: string, format?: string, frameTags?: { from: number, name: string, to: number, direction: string }[], image?: string, layers?: { blendMode: string, name: string, opacity: number }[], scale: number | string, size?: { h: number, w: number }, slices?: { color: string, name: string, keys: { frame: number, bounds: { x: number, y: number, w: number, h: number } }[] }[], related_multi_packs?: string[], version?: string} | The meta data of the atlas. |
Represents the JSON data for a spritesheet atlas.
Name | Type | Description |
---|---|---|
anchor | PointData | The anchor point of the texture. |
borders | TextureBorders | The 9-slice borders of the texture. |
frame | { x: number, y: number, w: number, h: number} | The frame rectangle of the texture. |
rotated | boolean | Whether the texture is rotated. |
sourceSize | { w: number, h: number} | The source size of the texture. |
spriteSourceSize | { h?: number, w?: number, x: number, y: number} | The sprite source size. |
trimmed | boolean | Whether the texture is trimmed. |
Options for loading a spritesheet from an atlas.
Name | Type | Description |
---|---|---|
cachePrefix | string | Prefix to add to texture names when adding to global TextureCache, using this option can be helpful if you have multiple texture atlases that share texture names and you need to disambiguate them. |
data | S | JSON data for the atlas. |
resolutionFilename | string | The filename to consider when determining the resolution of the spritesheet. |
texture | BindableTexture | Reference to Texture |
Returns an object of textures from an array of textures to be cached
Detects if the browser supports the AVIF image format.
Adds some default image formats to the detection parser
Detects if the browser supports the MP4 video format.
Detects if the browser supports the OGV video format.
Detects if the browser supports the WebM video format.
Detects if the browser supports the WebP image format.
A simple loader plugin for loading json data
A simple loader plugin for loading json data
A simple plugin to load our textures! This makes use of imageBitmaps where available. We load the ImageBitmap
on a different thread using workers if possible. We can then use the ImageBitmap
as a source for a Pixi texture
You can customize the behavior of this loader by setting the config
property. Which can be found here
// Set the configimport { loadTextures } from'pixi.js';
loadTextures.config = {
// If true we will use a worker to load the ImageBitmappreferWorkers: true,
// If false we will use new Image() instead of createImageBitmap,// we'll also disable the use of workers as it requires createImageBitmappreferCreateImageBitmap: true,
crossOrigin: 'anonymous',
};
A simple loader plugin for loading text data
A simple plugin to load video textures.
You can pass VideoSource options to the loader via the .data property of the asset descriptor when using Asset.load().
// Set the dataconst texture = await Assets.load({
src: './assets/city.mp4',
data: {
preload: true,
autoPlay: true,
},
});
A loader plugin for handling web fonts
import { Assets } from 'pixi.js';
Assets.load({
alias: 'font',
src: 'fonts/titan-one.woff',
data: {
family: 'Titan One',
weights: ['normal', 'bold'],
}
})
A parser that will resolve a json urls resolution for spritesheets e.g. assets/[email protected]
A parser that will resolve a texture url
Asset extension for loading spritesheets
import { Assets } from 'pixi.js';
Assets.load({
alias: 'spritesheet',
src: 'path/to/spritesheet.json',
data: {
ignoreMultiPack: true,
textureOptions: {
scaleMode: "nearest"
}
}
})
See assets_types.ts.html:53
A valid asset src. This can be a string, or a ResolvedSrc, or an array of either.
See assets_loader_parsers_loadWebFont.ts.html:25
Data for loading a font
Name | Type | Description |
---|---|---|
display | string | A set of optional descriptors passed as an object. It can contain any of the descriptors available for @font-face: |
family | string | Font family name |
featureSettings | string | The featureSettings property of the FontFace interface retrieves or sets infrequently used font features that are not available from a font's variant properties. |
stretch | string | The stretch property of the FontFace interface retrieves or sets how the font stretches. |
style | string | The style property of the FontFace interface retrieves or sets the font's style. |
unicodeRange | string | The unicodeRange property of the FontFace interface retrieves or sets the range of unicode code points encompassing the font. |
variant | string | The variant property of the FontFace interface programmatically retrieves or sets font variant values. |
weights | string[] | The weight property of the FontFace interface retrieves or sets the weight of the font. |
See assets_types.ts.html:3
Names of the parsers that are built into PixiJS. Can be any of the following defaults:
loadJson
loadSVG
loadTextures
loadTxt
loadVideo
loadWebFont
or a custom parser name.
See assets_Assets.ts.html:33
Callback for when progress on asset loading is made. The function is passed a single parameter, progress
, which represents the percentage (0.0 - 1.0) of the assets loaded.
Name | Type | Description |
---|---|---|
progress | number | The percentage (0.0 - 1.0) of the assets loaded. |
(progress) => console.log(progress * 100 + '%')
See assets_types.ts.html:42
A fully resolved src, Glob patterns will not work here, and the src will be resolved to a single file.
Name | Type | Description |
---|---|---|
data | any | Optional data |
format | string | Format, usually the file extension |
loadParser | string | An override that will ensure that the asset is loaded with a specific parser |
src | string | The URL or relative path to the asset |
See assets_types.ts.html:60
An asset that has not been resolved yet.
Name | Type | Description |
---|---|---|
alias | ArrayOr<string> | Aliases associated with asset |
src | AssetSrc | The URL or relative path to the asset |
See assets_loader_parsers_textures_loadVideoTextures.ts.html:18
Set cross origin based detecting the url and the crossorigin
Name | Type | Attributes | Description |
---|---|---|---|
element | HTMLImageElement | HTMLVideoElement | Element to apply crossOrigin | |
url | string | URL to check | |
crossorigin | boolean | string | <optional> | Cross origin value to use |
See assets_loader_parsers_loadWebFont.ts.html:60
Return font face name from a file name Ex.: 'fonts/titan-one.woff' turns into 'Titan One'
Name | Type | Description |
---|---|---|
url | string | File url |
Type | Description |
---|---|
string |
This developer convenience object allows developers to group together the various asset parsers into a single object.
import { AssetExtension, extensions } from 'pixi.js';
// create the CacheParser
const cache = {
test(asset: item): boolean {
// Gets called by the cache when a dev caches an asset
},
getCacheableAssets(keys: string[], asset: item): Record<string, any> {
// If the test passes, this function is called to get the cacheable assets
// an example may be that a spritesheet object will return all the sub textures it has so they can
// be cached.
},
};
// create the ResolveURLParser
const resolver = {
test(value: string): boolean {
// the test to perform on the url to determine if it should be parsed
},
parse(value: string): ResolvedAsset {
// the function that will convert the url into an object
},
};
// create the LoaderParser
const loader = {
name: 'itemLoader',
extension: {
type: ExtensionType.LoadParser,
},
async testParse(asset: any, options: ResolvedAsset) {
// This function is used to test if the parse function should be run on the asset
},
async parse(asset: any, options: ResolvedAsset, loader: Loader) {
// Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
},
unload(item: any) {
// If an asset is parsed using this parser, the unload function will be called when the user requests an asset
// to be unloaded. This is useful for things like sounds or textures that can be unloaded from memory
},
};
// put it all together and create the AssetExtension
extensions.add({
extension: ExtensionType.Asset,
cache,
resolver,
loader,
}
A more verbose version of the AssetExtension, allowing you to set the cached, loaded, parsed, and unloaded asset separately
Name | Type | Description |
---|---|---|
cache | Partial<CACHE_ASSET<CacheParser>> | the asset cache parser |
detection | Partial<FormatDetectionParser> | the asset format detection parser |
extension | Asset | The type of extension |
loader | LoaderParserAdvanced<META_DATA, ASSET, PARSED_ASSET, UNLOAD_ASSET> | the asset loader |
resolver | Partial<ResolveURLParser> | the asset resolve parser |
cachePartial<CACHE_ASSET<CacheParser>>
the asset cache parser
detectionPartial<FormatDetectionParser>
the asset format detection parser
extensionAsset
The type of extension
loaderLoaderParserAdvanced<META_DATA, ASSET, PARSED_ASSET, UNLOAD_ASSET>
the asset loader
resolverPartial<ResolveURLParser>
the asset resolve parser
Initialization options object for the Assets Class.
Name | Type | Description |
---|---|---|
basePath | string | a base path for any assets loaded |
bundleIdentifier | BundleIdentifierOptions | advanced - override how bundlesIds are generated |
defaultSearchParams | string | Record<string, any> | a default URL parameter string to append to all assets loaded |
manifest | string | AssetsManifest | a manifest to tell the asset loader upfront what all your assets are this can be the manifest object itself, or a URL to the manifest. |
preferences | Partial<AssetsPreferences> | Optional loader preferences |
skipDetections | boolean | If true, don't attempt to detect whether browser has preferred formats available. May result in increased performance as it skips detection step. |
texturePreference | { resolution?: number | number[], format?: ArrayOr<string>} | optional preferences for which textures preferences you have when resolving assets for example you might set the resolution to 0.5 if the user is on a rubbish old phone or you might set the resolution to 2 if the user is on a retina display |
a base path for any assets loaded
bundleIdentifierBundleIdentifierOptions
advanced - override how bundlesIds are generated
a default URL parameter string to append to all assets loaded
manifeststring | AssetsManifest
a manifest to tell the asset loader upfront what all your assets are this can be the manifest object itself, or a URL to the manifest.
preferencesPartial<AssetsPreferences>
Optional loader preferences
If true, don't attempt to detect whether browser has preferred formats available. May result in increased performance as it skips detection step.
optional preferences for which textures preferences you have when resolving assets for example you might set the resolution to 0.5 if the user is on a rubbish old phone or you might set the resolution to 2 if the user is on a retina display
The global Assets class, it's a singleton so you don't need to instantiate it.
The Assets
class has four main responsibilities:
- Allows users to map URLs to keys and resolve them according to the user's browser capabilities
- Loads the resources and transforms them into assets that developers understand.
- Caches the assets and provides a way to access them.
- Allow developers to unload assets and clear the cache.
It also has a few advanced features:
- Allows developers to provide a assets.Manifest upfront of all assets and help manage them via Bundles.
- Allows users to background load assets. Shortening (or eliminating) load times and improving UX. With this feature, in-game loading bars can be a thing of the past!
import { Assets } from 'pixi.js';
const bunny = await Assets.load('bunny.png');
cacheCache
The global cache of all assets within PixiJS
detectionsFormatDetectionParser[]
All the detection parsers currently added to the Assets class.
loaderLoader
The loader, loads stuff!
resolverResolver
the resolver to map various urls
See assets_Assets.ts.html:381
Allows you to specify how to resolve any assets load requests. There are a few ways to add things here as shown below:
Name | Type | Description |
---|---|---|
assets | (ArrayOr<UnresolvedAsset>) | the unresolved assets to add to the resolver |
import { Assets } from 'pixi.js';
// Simple
Assets.add({alias: 'bunnyBooBoo', src: 'bunny.png'});
const bunny = await Assets.load('bunnyBooBoo');
// Multiple keys:
Assets.add({alias: ['burger', 'chicken'], src: 'bunny.png'});
const bunny = await Assets.load('burger');
const bunny2 = await Assets.load('chicken');
// passing options to to the object
Assets.add({
alias: 'bunnyBooBooSmooth',
src: 'bunny.{png,webp}',
data: { scaleMode: SCALE_MODES.NEAREST }, // Base texture options
});
// Multiple assets
// The following all do the same thing:
Assets.add({alias: 'bunnyBooBoo', src: 'bunny.{png,webp}'});
Assets.add({
alias: 'bunnyBooBoo',
src: [
'bunny.png',
'bunny.webp',
],
});
const bunny = await Assets.load('bunnyBooBoo'); // Will try to load WebP if available
See assets_Assets.ts.html:500
This adds a bundle of assets in one go so that you can load them as a group. For example you could add a bundle for each screen in you pixi app
Name | Type | Description |
---|---|---|
bundleId | string | the id of the bundle to add |
assets | AssetsBundle["assets"] | a record of the asset or assets that will be chosen from when loading via the specified key |
import { Assets } from 'pixi.js';
Assets.addBundle('animals', [
{ alias: 'bunny', src: 'bunny.png' },
{ alias: 'chicken', src: 'chicken.png' },
{ alias: 'thumper', src: 'thumper.png' },
]);
// or
Assets.addBundle('animals', {
bunny: 'bunny.png',
chicken: 'chicken.png',
thumper: 'thumper.png',
});
const assets = await Assets.loadBundle('animals');
See assets_Assets.ts.html:623
Initiate a background load of some assets. It will passively begin to load these assets in the background. So when you actually come to loading them you will get a promise that resolves to the loaded assets immediately
An example of this might be that you would background load game assets after your initial load. then when you got to actually load your game screen assets when a player goes to the game - the loading would already have stared or may even be complete, saving you having to show an interim load bar.
Name | Type | Description |
---|---|---|
urls | ArrayOr<string> | the url / urls you want to background load |
Type | Description |
---|---|
Promise<void> |
import { Assets } from 'pixi.js';
Assets.backgroundLoad('bunny.png');
// later on in your app...
await Assets.loadBundle('bunny.png'); // Will resolve quicker as loading may have completed!
See assets_Assets.ts.html:656
Initiate a background of a bundle, works exactly like backgroundLoad but for bundles. this can only be used if the loader has been initiated with a manifest
Name | Type | Description |
---|---|---|
bundleIds | ArrayOr<string> | the bundleId / bundleIds you want to background load |
Type | Description |
---|---|
Promise<void> |
import { Assets } from 'pixi.js';
await Assets.init({
manifest: {
bundles: [
{
name: 'load-screen',
assets: [...],
},
...
],
},
});
Assets.backgroundLoadBundle('load-screen');
// Later on in your app...
await Assets.loadBundle('load-screen'); // Will resolve quicker as loading may have completed!
See assets_Assets.ts.html:714
Instantly gets an asset already loaded from the cache. If the asset has not yet been loaded, it will return undefined. So it's on you! When in doubt just use Assets.load
instead. (Remember, the loader will never load things more than once!)
Name | Type | Description |
---|---|---|
keys | ArrayOr<string> | The key or keys for the assets that you want to access |
Type | Description |
---|---|
T | T<string, Record> |
|
See assets_Assets.ts.html:312
Best practice is to call this function before any loading commences Initiating is the best time to add any customization to the way things are loaded.
you do not need to call this for the Assets class to work, only if you want to set any initial properties
Name | Type | Description |
---|---|---|
options | AssetInitOptions | options to initialize the Assets manager with |
Type | Description |
---|---|
Promise<void> |
See assets_Assets.ts.html:426
Loads your assets! You pass in a key or URL and it will return a promise that resolves to the loaded asset. If multiple assets a requested, it will return a hash of assets.
Don't worry about loading things multiple times, behind the scenes assets are only ever loaded once and the same promise reused behind the scenes so you can safely call this function multiple times with the same key and it will always return the same asset.
Name | Type | Attributes | Description |
---|---|---|---|
urls | ArrayOr<string> | UnresolvedAsset<ArrayOr> | the urls to load | |
onProgress | ProgressCallback | <optional> | optional function that is called when progress on asset loading is made. The function is passed a single parameter, progress , which represents the percentage (0.0 - 1.0) of the assets loaded. |
Type | Description |
---|---|
Promise<T | Record<string, T>> |
|
import { Assets } from 'pixi.js';
// Load a URL:
const myImageTexture = await Assets.load('http://some.url.com/image.png'); // => returns a texture
Assets.add('thumper', 'bunny.png');
Assets.add('chicko', 'chicken.png');
// Load multiple assets:
const textures = await Assets.load(['thumper', 'chicko']); // => {thumper: Texture, chicko: Texture}
See assets_Assets.ts.html:527
Bundles are a way to load multiple assets at once. If a manifest has been provided to the init function then you can load a bundle, or bundles. you can also add bundles via addBundle
Name | Type | Attributes | Description |
---|---|---|---|
bundleIds | ArrayOr<string> | the bundle id or ids to load | |
onProgress | ProgressCallback | <optional> | Optional function that is called when progress on asset loading is made. The function is passed a single parameter, progress , which represents the percentage (0.0 - 1.0) of the assets loaded. Do not use this function to detect when assets are complete and available, instead use the Promise returned by this function. |
Type | Description |
---|---|
Promise<any> | all the bundles assets or a hash of assets for each bundle specified |
import { Assets } from 'pixi.js';
// Manifest Example
const manifest = {
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',
},
],
},
]
};
await Assets.init({ manifest });
// Load a bundle...
loadScreenAssets = await Assets.loadBundle('load-screen');
// Load another bundle...
gameScreenAssets = await Assets.loadBundle('game-screen');
See assets_Assets.ts.html:700
Only intended for development purposes. This will wipe the resolver and caches. You will need to reinitialize the Asset
See assets_Assets.ts.html:927
General setter for preferences. This is a helper function to set preferences on all parsers.
Name | Type | Description |
---|---|---|
preferences | Partial<AssetsPreferences> | the preferences to set |
See assets_Assets.ts.html:786
Unload an asset or assets. As the Assets class is responsible for creating the assets via the load
function this will make sure to destroy any assets and release them from memory. Once unloaded, you will need to load the asset again.
Use this to help manage assets if you find that you have a large app and you want to free up memory.
- it's up to you as the developer to make sure that textures are not actively being used when you unload them, Pixi won't break but you will end up with missing assets. Not a good look for the user!
Name | Type | Description |
---|---|---|
urls | ArrayOr<string> | ResolvedAsset | ResolvedAsset[] | the urls to unload |
Type | Description |
---|---|
Promise<void> |
import { Assets } from 'pixi.js';
// Load a URL:
const myImageTexture = await Assets.load('http://some.url.com/image.png'); // => returns a texture
await Assets.unload('http://some.url.com/image.png')
// myImageTexture will be destroyed now.
// Unload multiple assets:
const textures = await Assets.unload(['thumper', 'chicko']);
See assets_Assets.ts.html:828
Bundles are a way to manage multiple assets at once. this will unload all files in a bundle.
once a bundle has been unloaded, you need to load it again to have access to the assets.
Name | Type | Description |
---|---|---|
bundleIds | ArrayOr<string> | the bundle id or ids to unload |
Type | Description |
---|---|
Promise<void> |
import { Assets } from 'pixi.js';
Assets.addBundle({
'thumper': 'http://some.url.com/thumper.png',
})
const assets = await Assets.loadBundle('thumper');
// Now to unload...
await Assets.unloadBundle('thumper');
// All assets in the assets object will now have been destroyed and purged from the cache
Structure of a bundle found in a Manifest file
Name | Type | Description |
---|---|---|
assets | UnresolvedAsset[] | UnresolvedAsset<string, ArrayOr<string> | Record> | The assets in the bundle |
name | string | The name of the bundle |
assetsUnresolvedAsset[] | UnresolvedAsset<string, ArrayOr<string> | Record>
The assets in the bundle
The name of the bundle
The expected format of a manifest. This could be auto generated or hand made
Name | Type | Description |
---|---|---|
bundles | AssetsBundle[] | array of bundles |
bundlesAssetsBundle[]
array of bundles
Extensible preferences that can be used, for instance, when configuring loaders.
Since:
: - 7.2.0
- LoadTextureConfig
- LoadSVGConfig
- PixiMixins.AssetsPreferences
Quietly Loads assets in the background.
See assets_BackgroundLoader.ts.html:26
Name | Type | Default | Description |
---|---|---|---|
loader | Loader | ||
verbose | boolean | false | should the loader log to the console |
Activate/Deactivate the loading. If set to true then it will immediately continue to load the next asset.
Should the loader log to the console.
See assets_BackgroundLoader.ts.html:39
Adds an array of assets to load.
Name | Type | Description |
---|---|---|
assetUrls | ResolvedAsset[] | assets to load |
Options for how the resolver deals with generating bundle ids
Name | Type | Description |
---|---|---|
connector | string | The character that is used to connect the bundleId and the assetId when generating a bundle asset id key |
createBundleAssetId | (bundleId: string, assetId: string) => string | A function that generates a bundle asset id key from a bundleId and an assetId |
extractAssetIdFromBundle | (bundleId: string, assetBundleId: string) => string | A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId |
The character that is used to connect the bundleId and the assetId when generating a bundle asset id key
A function that generates a bundle asset id key from a bundleId and an assetId
A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId
A single Cache for all assets.
When assets are added to the cache via set they normally are added to the cache as key-value pairs.
With this cache, you can add parsers that will take the object and convert it to a list of assets that can be cached. for example a cacheSpritesheet parser will add all of the textures found within its sprite sheet directly to the cache.
This gives devs the flexibility to cache any type of object however we want.
It is not intended that this class is created by developers - it is part of the Asset package. This is the first major system of PixiJS' main Assets class.
A single Cache for all assets.
import { Cache } from 'pixi.js';
Cache.set('bunny', bunnyTexture);
parsersCacheParser[]
All loader parsers registered
See assets_cache_Cache.ts.html:51
Fetch entry by key
Name | Type | Description |
---|---|---|
key | any | The key of the entry to get |
Type | Description |
---|---|
T |
See assets_cache_Cache.ts.html:42
Check if the key exists
Name | Type | Description |
---|---|---|
key | any | The key to check |
Type | Description |
---|---|
boolean |
See assets_cache_Cache.ts.html:131
Remove entry by key
This function will also remove any associated alias from the cache also.
Name | Type | Description |
---|---|---|
key | any | The key of the entry to remove |
See assets_cache_Cache.ts.html:35
Clear all entries.
See assets_cache_Cache.ts.html:69
Set a value by key or keys name
Name | Type | Description |
---|---|---|
key | any | any[] | The key or keys to set |
value | unknown | The value to store in the cache or from which cacheable assets will be derived. |
For every asset that is cached, it will call the parsers test function the flow is as follows:
cacheParser.test()
: Test the asset.cacheParser.getCacheableAssets()
: If the test passes call the getCacheableAssets function with the asset
Useful if you want to add more than just a raw asset to the cache (for example a spritesheet will want to make all its sub textures easily accessible in the cache)
Name | Type | Description |
---|---|---|
config | Record<string, any> | A config to adjust the parser |
extension | ExtensionMetadata | The extension type of this cache parser |
getCacheableAssets | (keys: string[], asset: T) => Record<string, any> | If the test passes, this function is called to get the cacheable assets an example may be that a spritesheet object will return all the sub textures it has so they can be cached. |
test | (asset: T) => boolean | Gets called by the cache when a dev caches an asset |
A config to adjust the parser
extensionExtensionMetadata
The extension type of this cache parser
If the test passes, this function is called to get the cacheable assets an example may be that a spritesheet object will return all the sub textures it has so they can be cached.
Gets called by the cache when a dev caches an asset
Format detection is useful for detecting feature support on the current platform.
Name | Type | Description |
---|---|---|
add | (formats: string[]) => Promise<string[]> | Add formats (file extensions) to the existing list of formats. Return an new array with added formats, do not mutate the formats argument. |
extension | ExtensionMetadata | Should be ExtensionType.DetectionParser |
remove | (formats: string[]) => Promise<string[]> | Remove formats (file extensions) from the list of supported formats. This is used when uninstalling this DetectionParser. Return an new array with filtered formats, do not mutate the formats argument. |
test | () => Promise<boolean> | Browser/platform feature detection supported if return true |
Add formats (file extensions) to the existing list of formats. Return an new array with added formats, do not mutate the formats argument.
extensionExtensionMetadata
Should be ExtensionType.DetectionParser
Remove formats (file extensions) from the list of supported formats. This is used when uninstalling this DetectionParser. Return an new array with filtered formats, do not mutate the formats argument.
Browser/platform feature detection supported if return true
The Loader is responsible for loading all assets, such as images, spritesheets, audio files, etc. It does not do anything clever with URLs - it just loads stuff! Behind the scenes all things are cached using promises. This means it's impossible to load an asset more than once. Through the use of LoaderParsers, the loader can understand how to load any kind of file!
It is not intended that this class is created by developers - its part of the Asset class This is the second major system of PixiJS' main Assets class
parsersArray<LoaderParser>
All loader parsers registered
promiseCacheRecord<string, PromiseAndParser>
Cache loading promises that ae currently active
See assets_loader_Loader.ts.html:136
Loads one or more assets using the parsers added to the Loader.
Name | Type | Attributes | Description |
---|---|---|---|
assetsToLoadIn | string | string[] | ResolvedAsset | ResolvedAsset[] | urls that you want to load, or a single one! | |
onProgress | (progress: number) => void | <optional> | For multiple asset loading only, an optional function that is called when progress on asset loading is made. The function is passed a single parameter, progress , which represents the percentage (0.0 - 1.0) of the assets loaded. Do not use this function to detect when assets are complete and available, instead use the Promise returned by this function. |
Type | Description |
---|---|
Promise<T | Record<string, T>> |
// Single asset:
const asset = await Loader.load('cool.png');
console.log(asset);
// Multiple assets:
const assets = await Loader.load(['cool.png', 'cooler.png']);
console.log(assets);
See assets_loader_Loader.ts.html:45
function used for testing
See assets_loader_Loader.ts.html:220
Unloads one or more assets. Any unloaded assets will be destroyed, freeing up memory for your app. The parser that created the asset, will be the one that unloads it.
Name | Type | Description |
---|---|---|
assetsToUnloadIn | string | string[] | ResolvedAsset | ResolvedAsset[] | urls that you want to unload, or a single one! |
Type | Description |
---|---|
Promise<void> |
// Single asset:
const asset = await Loader.load('cool.png');
await Loader.unload('cool.png');
console.log(asset.destroyed); // true
The interface to define a loader parser (all functions are optional).
When you create a parser
object, the flow for every asset loaded is:
parser.test()
- Each URL to load will be tested here, if the test is passed the assets are loaded using the load function below. Good place to test for things like file extensions!parser.load()
- This is the promise that loads the URL provided resolves with a loaded asset if returned by the parser.parser.testParse()
- This function is used to test if the parse function should be run on the asset If this returns true then parse is called with the assetparse.parse()
- Gets called on the asset it testParse passes. Useful to convert a raw asset into something more useful
Some loaders may only be used for parsing, some only for loading, and some for both!
Configuration for the loadSVG plugin.
Name | Type | Default | Description |
---|---|---|---|
crossOrigin | HTMLImageElement["crossOrigin"] | 'anonymous' | The crossOrigin value to use for loading the SVG as an image. |
parseAsGraphicsContext | boolean | false | When set to true , loading and decoding images will happen with new Image() , |
See: assets.loadSVG
The crossOrigin value to use for loading the SVG as an image.
Default Value:
: - 'anonymous'
When set to true
, loading and decoding images will happen with new Image()
,
Default Value:
: - false
Configuration for the loadTextures plugin.
Name | Type | Default | Description |
---|---|---|---|
crossOrigin | HTMLImageElement["crossOrigin"] | 'anonymous' | The crossOrigin value to use for images when preferCreateImageBitmap is false . |
preferCreateImageBitmap | boolean | true | When set to true , loading and decoding images will happen with createImageBitmap , otherwise it will use new Image() . |
preferWorkers | boolean | true | When set to true , loading and decoding images will happen with Worker thread, if available on the browser. This is much more performant as network requests and decoding can be expensive on the CPU. However, not all environments support Workers, in some cases it can be helpful to disable by setting to false . |
See: loadTextures
The crossOrigin value to use for images when preferCreateImageBitmap
is false
.
Default Value:
: - 'anonymous'
When set to true
, loading and decoding images will happen with createImageBitmap
, otherwise it will use new Image()
.
Default Value:
: - true
When set to true
, loading and decoding images will happen with Worker thread, if available on the browser. This is much more performant as network requests and decoding can be expensive on the CPU. However, not all environments support Workers, in some cases it can be helpful to disable by setting to false
.
Default Value:
: - true
A prefer order lets the resolver know which assets to prefer depending on the various parameters passed to it.
Name | Type | Description |
---|---|---|
priority | string[] | the importance order of the params |
the importance order of the params
A promise and parser pair
Name | Type | Description |
---|---|---|
parser | LoaderParser | the parser that is loading the asset |
promise | Promise<any> | the promise that is loading the asset |
parserLoaderParser
the parser that is loading the asset
the promise that is loading the asset
A fully resolved asset, with all the information needed to load it.
Name | Type | Description |
---|---|---|
alias | string[] | Aliases associated with asset |
data | T | Optional data |
format | string | Format, usually the file extension |
loadParser | LoadParserName | An override that will ensure that the asset is loaded with a specific parser |
src | string | The URL or relative path to the asset |
Aliases associated with asset
Optional data
Format, usually the file extension
loadParserLoadParserName
An override that will ensure that the asset is loaded with a specific parser
The URL or relative path to the asset
A class that is responsible for resolving mapping asset URLs to keys. At its most basic it can be used for Aliases:
resolver.add('foo', 'bar');
resolver.resolveUrl('foo') // => 'bar'
It can also be used to resolve the most appropriate asset for a given URL:
resolver.prefer({
params: {
format: 'webp',
resolution: 2,
}
});
resolver.add('foo', ['[email protected]', '[email protected]', 'bar.webp', 'bar.png']);
resolver.resolveUrl('foo') // => '[email protected]'
Other features include:
- Ability to process a manifest file to get the correct understanding of how to resolve all assets
- Ability to add custom parsers for specific file types
- Ability to add custom prefer rules
This class only cares about the URL, not the loading of the asset itself.
It is not intended that this class is created by developers - its part of the Asset class This is the third major system of PixiJS' main Assets class
The prefix that denotes a URL is for a retina asset.
Default Value:
: - /@([0-9\.]+)x/
`@2x`
Set the base path to prepend to all urls when resolving
resolver.basePath = 'https://home.com/';
resolver.add('foo', 'bar.ong');
resolver.resolveUrl('foo', 'bar.png'); // => 'https://home.com/bar.png'
parsersResolveURLParser[]
All the active URL parsers that help the parser to extract information and create an asset object-based on parsing the URL itself.
Can be added using the extensions API
resolver.add('foo', [
{
resolution: 2,
format: 'png',
src: '[email protected]',
},
{
resolution:1,
format:'png',
src: 'image.png',
},
]);
// With a url parser the information such as resolution and file format could extracted from the url itself:
extensions.add({
extension: ExtensionType.ResolveParser,
test: loadTextures.test, // test if url ends in an image
parse: (value: string) =>
({
resolution: parseFloat(Resolver.RETINA_PREFIX.exec(value)?.[1] ?? '1'),
format: value.split('.').pop(),
src: value,
}),
});
// Now resolution and format can be extracted from the url
resolver.add('foo', [
'[email protected]',
'image.png',
]);
Set the root path for root-relative URLs. By default the basePath
's root is used. If no basePath
is set, then the default value for browsers is window.location.origin
// Application hosted on https://home.com/some-path/index.html
resolver.basePath = 'https://home.com/some-path/';
resolver.rootPath = 'https://home.com/';
resolver.add('foo', '/bar.png');
resolver.resolveUrl('foo', '/bar.png'); // => 'https://home.com/bar.png'
See assets_resolver_Resolver.ts.html:420
Tells the resolver what keys are associated with witch asset. The most important thing the resolver does
Name | Type | Description |
---|---|---|
aliases | ArrayOr<UnresolvedAsset> | the UnresolvedAsset or array of UnresolvedAssets to add to the resolver |
// Single key, single asset:
resolver.add({alias: 'foo', src: 'bar.png');
resolver.resolveUrl('foo') // => 'bar.png'
// Multiple keys, single asset:
resolver.add({alias: ['foo', 'boo'], src: 'bar.png'});
resolver.resolveUrl('foo') // => 'bar.png'
resolver.resolveUrl('boo') // => 'bar.png'
// Multiple keys, multiple assets:
resolver.add({alias: ['foo', 'boo'], src: ['bar.png', 'bar.webp']});
resolver.resolveUrl('foo') // => 'bar.png'
// Add custom data attached to the resolver
Resolver.add({
alias: 'bunnyBooBooSmooth',
src: 'bunny{png,webp}',
data: { scaleMode:SCALE_MODES.NEAREST }, // Base texture options
});
resolver.resolve('bunnyBooBooSmooth') // => { src: 'bunny.png', data: { scaleMode: SCALE_MODES.NEAREST } }
See assets_resolver_Resolver.ts.html:343
This adds a bundle of assets in one go so that you can resolve them as a group. For example you could add a bundle for each screen in you pixi app
Name | Type | Description |
---|---|---|
bundleId | string | The id of the bundle to add |
assets | AssetsBundle["assets"] | A record of the asset or assets that will be chosen from when loading via the specified key |
resolver.addBundle('animals', [
{ alias: 'bunny', src: 'bunny.png' },
{ alias: 'chicken', src: 'chicken.png' },
{ alias: 'thumper', src: 'thumper.png' },
]);
// or
resolver.addBundle('animals', {
bunny: 'bunny.png',
chicken: 'chicken.png',
thumper: 'thumper.png',
});
const resolvedAssets = await resolver.resolveBundle('animals');
See assets_resolver_Resolver.ts.html:321
Add a manifest to the asset resolver. This is a nice way to add all the asset information in one go. generally a manifest would be built using a tool.
Name | Type | Description |
---|---|---|
manifest | AssetsManifest | the manifest to add to the resolver |
See assets_resolver_Resolver.ts.html:299
Returns the aliases for a given asset
Name | Type | Description |
---|---|---|
asset | UnresolvedAsset | the asset to get the aliases for |
Type | Description |
---|---|
string[] |
See assets_resolver_Resolver.ts.html:741
Checks if a bundle with the given key exists in the resolver
Name | Type | Description |
---|---|---|
key | string | The key of the bundle |
Type | Description |
---|---|
boolean |
See assets_resolver_Resolver.ts.html:732
Checks if an asset with a given key exists in the resolver
Name | Type | Description |
---|---|---|
key | string | The key of the asset |
Type | Description |
---|---|
boolean |
See assets_resolver_Resolver.ts.html:149
Let the resolver know which assets you prefer to use when resolving assets. Multiple prefer user defined rules can be added.
Name | Type | Description |
---|---|---|
preferOrders | PreferOrder[] | the prefer options |
resolver.prefer({
// first look for something with the correct format, and then then correct resolution
priority: ['format', 'resolution'],
params:{
format:'webp', // prefer webp images
resolution: 2, // prefer a resolution of 2
}
})
resolver.add('foo', ['[email protected]', '[email protected]', 'bar.webp', 'bar.png']);
resolver.resolveUrl('foo') // => '[email protected]'
See assets_resolver_Resolver.ts.html:262
Used for testing, this resets the resolver to its initial state
resolve (keys)ResolvedAsset | ResolvedAsset<string, Record>
See assets_resolver_Resolver.ts.html:660
Resolves each key in the list to an asset object. Another key function of the resolver! After adding all the various key/asset pairs. this will run the logic of finding which asset to return based on any preferences set using the prefer
function by default the same key passed in will be returned if nothing is matched by the resolver.
Name | Type | Description |
---|---|---|
keys | ArrayOr<string> | key or keys to resolve |
Type | Description |
---|---|
ResolvedAsset | ResolvedAsset<string, Record> |
|
resolver.add('boo', 'bunny.png');
resolver.resolve('boo') // => { src: 'bunny.png' }
// Will return the same string as no key was added for this value..
resolver.resolve('another-thing.png') // => { src: 'another-thing.png' }
resolveBundle (bundleIds) Record<string, ResolvedAsset> | ResolvedAsset<string, Record<string, Record>>
See assets_resolver_Resolver.ts.html:562
If the resolver has had a manifest set via setManifest, this will return the assets urls for a given bundleId or bundleIds.
Name | Type | Description |
---|---|---|
bundleIds | ArrayOr<string> | The bundle ids to resolve |
Type | Description |
---|---|
Record<string, ResolvedAsset> | ResolvedAsset<string, Record<string, Record>> | All the bundles assets or a hash of assets for each bundle specified |
// Manifest Example
const manifest = {
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',
},
],
},
]
};
resolver.setManifest(manifest);
const resolved = resolver.resolveBundle('load-screen');
See assets_resolver_Resolver.ts.html:636
Does exactly what resolve does, but returns just the URL rather than the whole asset object
Name | Type | Description |
---|---|---|
key | ArrayOr<string> | The key or keys to resolve |
Type | Description |
---|---|
string | Record<string, string> |
|
See assets_resolver_Resolver.ts.html:132
Override how the resolver deals with generating bundle ids. must be called before any bundles are added
Name | Type | Description |
---|---|---|
bundleIdentifier | BundleIdentifierOptions | the bundle identifier options |
See assets_resolver_Resolver.ts.html:279
Sets the default URL search parameters for the URL resolver. The urls can be specified as a string or an object.
Name | Type | Description |
---|---|---|
searchParams | string | Record<string, unknown> | the default url parameters to append when resolving urls |
Format for url parser, will test a string and if it pass will then parse it, turning it into an ResolvedAsset
Name | Type | Description |
---|---|---|
config | Record<string, any> | A config to adjust the parser |
parse | (value: string) => ResolvedAsset & { [key: string]: any } | the function that will convert the url into an object |
test | (url: string) => boolean | the test to perform on the url to determine if it should be parsed |
A config to adjust the parser
the function that will convert the url into an object
the test to perform on the url to determine if it should be parsed
Utility class for maintaining reference to a collection of Textures on a single Spritesheet.
To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader:
import { Assets } from'pixi.js';
const sheet = await Assets.load('images/spritesheet.json');
Alternately, you may circumvent the loader by instantiating the Spritesheet directly:
import { Spritesheet } from'pixi.js';
const sheet = new Spritesheet(texture, spritesheetData);
await sheet.parse();
console.log('Spritesheet ready to use!');
With the sheet.textures
you can create Sprite objects, and sheet.animations
can be used to create an AnimatedSprite.
Here's an example of a sprite sheet JSON data file:
{
"frames": {
"enemy1.png":
{
"frame": {"x":103,"y":1,"w":32,"h":32},
"spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
"sourceSize": {"w":32,"h":32},
"anchor": {"x":0.5,"y":0.5}
},
"enemy2.png":
{
"frame": {"x":103,"y":35,"w":32,"h":32},
"spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
"sourceSize": {"w":32,"h":32},
"anchor": {"x":0.5,"y":0.5}
},
"button.png":
{
"frame": {"x":1,"y":1,"w":100,"h":100},
"spriteSourceSize": {"x":0,"y":0,"w":100,"h":100},
"sourceSize": {"w":100,"h":100},
"anchor": {"x":0,"y":0},
"borders": {"left":35,"top":35,"right":35,"bottom":35}
}
},
"animations": {
"enemy": ["enemy1.png","enemy2.png"]
},
"meta": {
"image": "sheet.png",
"format": "RGBA8888",
"size": {"w":136,"h":102},
"scale": "1"
}
}
Sprite sheets can be packed using tools like TexturePacker, Shoebox or Spritesheet.js. Default anchor points (see Texture#defaultAnchor), default 9-slice borders (see Texture#defaultBorders) and grouping of animation sprites are currently only supported by TexturePacker.
Alternative ways for loading spritesheet image if you need more control:
import { Assets } from'pixi.js';
const sheetTexture = await Assets.load('images/spritesheet.png');
Assets.add({
alias: 'atlas',
src: 'images/spritesheet.json',
data: {texture: sheetTexture} // using of preloaded texture
});
const sheet = await Assets.load('atlas')
or:
import { Assets } from'pixi.js';
Assets.add({
alias: 'atlas',
src: 'images/spritesheet.json',
data: {imageFilename: 'my-spritesheet.2x.avif'} // using of custom filename located in "images/my-spritesheet.2x.avif"
});
const sheet = await Assets.load('atlas')
See spritesheet_Spritesheet.ts.html:285
Name | Type | Description |
---|---|---|
texture | BindableTexture | Reference to the source BaseTexture object. |
data | object | Spritesheet image data. |
The maximum number of Textures to build per process.
Default Value:
: - 1000
animationsRecord<keyof, Texture[]>
A map containing the textures for each animation. Can be used to create an AnimatedSprite:
import { AnimatedSprite } from 'pixi.js';
new AnimatedSprite(sheet.animations['anim_name']);
Prefix string to add to global cache
Reference to the original JSON data.
linkedSheetsSpritesheet<S>[]
For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on.
The resolution of the spritesheet.
texturesRecord<keyof, Texture>
A map containing all textures of the sprite sheet. Can be used to create a Sprite:
import { Sprite } from 'pixi.js';
new Sprite(sheet.textures['image.png']);
textureSourceTextureSource
Reference to the source texture.
See spritesheet_Spritesheet.ts.html:476
Destroy Spritesheet and don't use after this.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
destroyBase | boolean | <optional> | false | Whether to destroy the base texture as well |
parse () Promise<Texture<string, Record>>
See spritesheet_Spritesheet.ts.html:329
Parser spritesheet from loaded data. This is done asynchronously to prevent creating too many Texture within a single process.
Type | Description |
---|---|
Promise<Texture<string, Record>> |
Name | Type | Description |
---|---|---|
options | SpritesheetOptions<S> | Options to use when constructing a new Spritesheet. |
Atlas format.
Name | Type | Description |
---|---|---|
animations | Dict<string[]> | The animations of the atlas. |
frames | Dict<SpritesheetFrameData> | The frames of the atlas. |
meta | { app?: string, format?: string, frameTags?: { from: number, name: string, to: number, direction: string }[], image?: string, layers?: { blendMode: string, name: string, opacity: number }[], scale: number | string, size?: { h: number, w: number }, slices?: { color: string, name: string, keys: { frame: number, bounds: { x: number, y: number, w: number, h: number } }[] }[], related_multi_packs?: string[], version?: string} | The meta data of the atlas. |
The animations of the atlas.
framesDict<SpritesheetFrameData>
The frames of the atlas.
meta{ app?: string, format?: string, frameTags?: { from: number, name: string, to: number, direction: string }[], image?: string, layers?: { blendMode: string, name: string, opacity: number }[], scale: number | string, size?: { h: number, w: number }, slices?: { color: string, name: string, keys: { frame: number, bounds: { x: number, y: number, w: number, h: number } }[] }[], related_multi_packs?: string[], version?: string}
The meta data of the atlas.
Represents the JSON data for a spritesheet atlas.
Name | Type | Description |
---|---|---|
anchor | PointData | The anchor point of the texture. |
borders | TextureBorders | The 9-slice borders of the texture. |
frame | { x: number, y: number, w: number, h: number} | The frame rectangle of the texture. |
rotated | boolean | Whether the texture is rotated. |
sourceSize | { w: number, h: number} | The source size of the texture. |
spriteSourceSize | { h?: number, w?: number, x: number, y: number} | The sprite source size. |
trimmed | boolean | Whether the texture is trimmed. |
anchorPointData
The anchor point of the texture.
bordersTextureBorders
The 9-slice borders of the texture.
The frame rectangle of the texture.
Whether the texture is rotated.
The source size of the texture.
The sprite source size.
Whether the texture is trimmed.
Options for loading a spritesheet from an atlas.
Name | Type | Description |
---|---|---|
cachePrefix | string | Prefix to add to texture names when adding to global TextureCache, using this option can be helpful if you have multiple texture atlases that share texture names and you need to disambiguate them. |
data | S | JSON data for the atlas. |
resolutionFilename | string | The filename to consider when determining the resolution of the spritesheet. |
texture | BindableTexture | Reference to Texture |
Prefix to add to texture names when adding to global TextureCache, using this option can be helpful if you have multiple texture atlases that share texture names and you need to disambiguate them.
JSON data for the atlas.
The filename to consider when determining the resolution of the spritesheet.
Reference to Texture
The BatchableHTMLText class extends the BatchableSprite class and is used to handle HTML text rendering. It includes a promise for the texture as generating the HTML texture takes some time.
See scene_text-html_BatchableHTMLText.ts.html:17
Creates an instance of BatchableHTMLText.
Name | Type | Description |
---|---|---|
renderer | Renderer | The renderer instance to be used. |
- BatchableSprite
See scene_text-html_BatchableHTMLText.ts.html:43
Destroys the BatchableHTMLText instance. Returns the texture promise to the renderer and cleans up references.
See scene_text-html_BatchableHTMLText.ts.html:32
Handles resolution changes for the HTML text. If the text has auto resolution enabled, it triggers a view update.
See scene_sprite_BatchableSprite.ts.html:40
See scene_sprite_BatchableSprite.ts.html:40
See scene_sprite_BatchableSprite.ts.html:40
An interface for a pipe that can be used to build instructions for the renderer. BatchPipes are specifically used to build and render Batches.
Name | Type | Description |
---|---|---|
addToBatch | (renderable: BatchableElement, instructionSet: InstructionSet) => void | Add a add a batchable object to the batch. |
break | (instructionSet: InstructionSet) => void | Forces the batch to break. This can happen if for example you need to render everything and then change the render target. |
addToBatch(renderable: BatchableElement, instructionSet: InstructionSet) => void
Add a add a batchable object to the batch.
break(instructionSet: InstructionSet) => void
Forces the batch to break. This can happen if for example you need to render everything and then change the render target.
new BitmapTextGraphics ()overrides
From class Graphics
The local bounds of the graphic.
fillStyleConvertedFillStyleinherited
The fill style to use.
strokeStyleConvertedStrokeStyleinherited
The stroke style to use.
From class Container
accessiblebooleaninherited
Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set
Default Value:
: - false
accessibleChildrenbooleaninherited
Setting to false will prevent any children inside this container to be accessible. Defaults to true.
Default Value:
: - true
accessibleHintstringinherited
Sets the aria-label attribute of the shadow div
Default Value:
: - undefined
accessiblePointerEventsPointerEventsinherited
Specify the pointer-events the accessible div will use Defaults to auto.
Default Value:
: - 'auto'
accessibleTextstringinherited
Sets the text content of the shadow div
Default Value:
: - undefined
accessibleTitlestringinherited
Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]'
Default Value:
: - undefined
accessibleTypestringinherited
Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button.
Default Value:
: - 'button'
alphanumberinherited
The opacity of the object.
anglenumberinherited
The angle of the object in degrees. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
blendModeBLEND_MODESinherited
The blend mode to be applied to the sprite. Apply a value of 'normal'
to reset the blend mode.
Default Value:
: - 'normal'
An optional bounds area for this container. Setting this rectangle will stop the renderer from recursively measuring the bounds of each children and instead use this single boundArea. This is great for optimisation! If for example you have a 1000 spinning particles and you know they all sit within a specific bounds, then setting it will mean the renderer will not need to measure the 1000 children to find the bounds. Instead it will just use the bounds you set.
cacheAsBitmapbooleanDeprecated : Since PixiJS v8inherited
Legacy property for backwards compatibility with PixiJS v7 and below. Use cacheAsTexture
instead.
childrenC[]readonlyinherited
The array of children of this container.
cullablebooleaninherited
Should this object be rendered if the bounds of this object are out of frame?
Culling has no effect on whether updateTransform is called.
Default Value:
: - false
cullableChildrenbooleaninherited
Determines if the children to the container can be culled Setting this to false allows PixiJS to bypass a recursive culling function Which can help to optimize very complex scenes
Default Value:
: - true
If set, this shape is used for culling instead of the bounds of this object. It can improve the culling performance of objects with many children. The culling area is defined in local space.
destroyedbooleaninherited
If the object has been destroyed via destroy(). If true, it should not be used.
Default Value:
: - false
effectsArray<Effect>inherited
TODO
: - Needs docs.
The group transform is a transform relative to the render group it belongs too. If this container is render group then this will be an identity matrix. other wise it will be the same as the relativeGroupTransform. Use this value when actually rendering things to the screen
heightnumberinherited
The height of the Container, setting this will actually modify the scale to achieve the value set.
hitAreaIHitAreainherited
Interaction shape. Children will be hit first, then this shape will be checked. Setting this will cause this shape to be checked in hit tests rather than the container's bounds.
Default Value:
: - undefined
import { Rectangle, Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.interactive = true;
sprite.hitArea = new Rectangle(0, 0, 100, 100);
interactiveChildrenbooleaninherited
Determines if the children to the container can be clicked/touched Setting this to false allows PixiJS to bypass a recursive hitTest
function
Default Value:
: - true
isCachedAsTexturebooleanreadonlyinherited
Whether this container is currently cached as a texture.
isRenderablebooleaninherited
Whether or not the object should be rendered.
isRenderGroupbooleaninherited
Returns true if this container is a render group. This means that it will be rendered as a separate pass, with its own set of instructions
labelstringinherited
The instance label of the object.
Default Value:
: - undefined
Current transform of the object based on local factors: position, scale, other stuff.
namestringDeprecated : since 8.0.0inherited
The instance name of the object.
See: label
onclickinherited
Property-based event handler for the click
event.
Default Value:
: - null
this.onclick = (event) => {
//some function here that happens on click
}
onglobalmousemoveinherited
Property-based event handler for the globalmousemove
event.
Default Value:
: - null
this.onglobalmousemove = (event) => {
//some function here that happens on globalmousemove
}
onglobalpointermoveinherited
Property-based event handler for the globalpointermove
event.
Default Value:
: - null
this.onglobalpointermove = (event) => {
//some function here that happens on globalpointermove
}
onglobaltouchmoveinherited
Property-based event handler for the globaltouchmove
event.
Default Value:
: - null
this.onglobaltouchmove = (event) => {
//some function here that happens on globaltouchmove
}
onmousedowninherited
Property-based event handler for the mousedown
event.
Default Value:
: - null
this.onmousedown = (event) => {
//some function here that happens on mousedown
}
onmouseenterinherited
Property-based event handler for the mouseenter
event.
Default Value:
: - null
this.onmouseenter = (event) => {
//some function here that happens on mouseenter
}
onmouseleaveinherited
Property-based event handler for the mouseleave
event.
Default Value:
: - null
this.onmouseleave = (event) => {
//some function here that happens on mouseleave
}
onmousemoveinherited
Property-based event handler for the mousemove
event.
Default Value:
: - null
this.onmousemove = (event) => {
//some function here that happens on mousemove
}
onmouseoutinherited
Property-based event handler for the mouseout
event.
Default Value:
: - null
this.onmouseout = (event) => {
//some function here that happens on mouseout
}
onmouseoverinherited
Property-based event handler for the mouseover
event.
Default Value:
: - null
this.onmouseover = (event) => {
//some function here that happens on mouseover
}
onmouseupinherited
Property-based event handler for the mouseup
event.
Default Value:
: - null
this.onmouseup = (event) => {
//some function here that happens on mouseup
}
onmouseupoutsideinherited
Property-based event handler for the mouseupoutside
event.
Default Value:
: - null
this.onmouseupoutside = (event) => {
//some function here that happens on mouseupoutside
}
onpointercancelinherited
Property-based event handler for the pointercancel
event.
Default Value:
: - null
this.onpointercancel = (event) => {
//some function here that happens on pointercancel
}
onpointerdowninherited
Property-based event handler for the pointerdown
event.
Default Value:
: - null
this.onpointerdown = (event) => {
//some function here that happens on pointerdown
}
onpointerenterinherited
Property-based event handler for the pointerenter
event.
Default Value:
: - null
this.onpointerenter = (event) => {
//some function here that happens on pointerenter
}
onpointerleaveinherited
Property-based event handler for the pointerleave
event.
Default Value:
: - null
this.onpointerleave = (event) => {
//some function here that happens on pointerleave
}
onpointermoveinherited
Property-based event handler for the pointermove
event.
Default Value:
: - null
this.onpointermove = (event) => {
//some function here that happens on pointermove
}
onpointeroutinherited
Property-based event handler for the pointerout
event.
Default Value:
: - null
this.onpointerout = (event) => {
//some function here that happens on pointerout
}
onpointeroverinherited
Property-based event handler for the pointerover
event.
Default Value:
: - null
this.onpointerover = (event) => {
//some function here that happens on pointerover
}
onpointertapinherited
Property-based event handler for the pointertap
event.
Default Value:
: - null
this.onpointertap = (event) => {
//some function here that happens on pointertap
}
onpointerupinherited
Property-based event handler for the pointerup
event.
Default Value:
: - null
this.onpointerup = (event) => {
//some function here that happens on pointerup
}
onpointerupoutsideinherited
Property-based event handler for the pointerupoutside
event.
Default Value:
: - null
this.onpointerupoutside = (event) => {
//some function here that happens on pointerupoutside
}
onrightclickinherited
Property-based event handler for the rightclick
event.
Default Value:
: - null
this.onrightclick = (event) => {
//some function here that happens on rightclick
}
onrightdowninherited
Property-based event handler for the rightdown
event.
Default Value:
: - null
this.onrightdown = (event) => {
//some function here that happens on rightdown
}
onrightupinherited
Property-based event handler for the rightup
event.
Default Value:
: - null
this.onrightup = (event) => {
//some function here that happens on rightup
}
onrightupoutsideinherited
Property-based event handler for the rightupoutside
event.
Default Value:
: - null
this.onrightupoutside = (event) => {
//some function here that happens on rightupoutside
}
ontapinherited
Property-based event handler for the tap
event.
Default Value:
: - null
this.ontap = (event) => {
//some function here that happens on tap
}
ontouchcancelinherited
Property-based event handler for the touchcancel
event.
Default Value:
: - null
this.ontouchcancel = (event) => {
//some function here that happens on touchcancel
}
ontouchendinherited
Property-based event handler for the touchend
event.
Default Value:
: - null
this.ontouchend = (event) => {
//some function here that happens on touchend
}
ontouchendoutsideinherited
Property-based event handler for the touchendoutside
event.
Default Value:
: - null
this.ontouchendoutside = (event) => {
//some function here that happens on touchendoutside
}
ontouchmoveinherited
Property-based event handler for the touchmove
event.
Default Value:
: - null
this.ontouchmove = (event) => {
//some function here that happens on touchmove
}
ontouchstartinherited
Property-based event handler for the touchstart
event.
Default Value:
: - null
this.ontouchstart = (event) => {
//some function here that happens on touchstart
}
onwheelinherited
Property-based event handler for the wheel
event.
Default Value:
: - null
this.onwheel = (event) => {
//some function here that happens on wheel
}
The display object container that contains this display object.
Default Value:
: - undefined
parentRenderLayerIRenderLayerreadonlyinherited
The RenderLayer this container belongs to, if any. If it belongs to a RenderLayer, it will be rendered from the RenderLayer's position in the scene.
The center of rotation, scaling, and skewing for this display object in its local space. The position
is the projection of pivot
in the parent's local space.
By default, the pivot is the origin (0, 0).
Since:
: - 4.0.0
positionObservablePointinherited
The coordinate of the object relative to the local coordinates of the parent.
Since:
: - 4.0.0
The relative group transform is a transform relative to the render group it belongs too. It will include all parent transforms and up to the render group (think of it as kind of like a stage - but the stage can be nested). If this container is is self a render group matrix will be relative to its parent render group
renderableinherited
Can this object be rendered, if false the object will not be drawn but the transform will still be updated.
rotationnumberinherited
The rotation of the object in radians. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
The scale factors of this object along the local coordinate axes.
The default scale is (1, 1).
Since:
: - 4.0.0
The skew factor for the object in radians.
Since:
: - 4.0.0
sortableChildrenbooleaninherited
If set to true, the container will sort its children by zIndex
value when the next render is called, or manually if sortChildren()
is called.
This actually changes the order of elements in the array, so should be treated as a basic solution that is not performant compared to other solutions, such as PixiJS Layers
Also be aware of that this may not work nicely with the addChildAt()
function, as the zIndex
sorting may cause the child to automatically sorted to another position.
Default Value:
: - false
sortDirtybooleaninherited
Should children be sorted by zIndex at the next render call.
Will get automatically set to true if a new child is added, or if a child's zIndex changes.
Default Value:
: - false
tabIndexnumberinherited
Default Value:
: - 0
TODO
: - Needs docs.
tintnumberinherited
The tint applied to the sprite. This is a hex value.
A value of 0xFFFFFF will remove any tint effect.
Default Value:
: - 0xFFFFFF
uidnumberreadonlyinherited
unique id for this container
updateCacheTexture() => voidinherited
Updates the cached texture of this container. This will flag the container's cached texture to be redrawn on the next render.
visibleinherited
The visibility of the object. If false the object will not be drawn, and the transform will not be updated.
widthnumberinherited
The width of the Container, setting this will actually modify the scale to achieve the value set.
worldTransformreadonlyinherited
Current transform of the object based on world (parent) factors.
xnumberinherited
The position of the container on the x axis relative to the local coordinates of the parent. An alias to position.x
ynumberinherited
The position of the container on the y axis relative to the local coordinates of the parent. An alias to position.y
From class Graphics
arc (...x, y, radius, startAngle, endAngle, counterclockwise) thisinherited
See scene_graphics_shared_Graphics.ts.html:258
Adds an arc to the current path, which is centered at (x, y) with the specified radius, starting and ending angles, and direction.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["arc"]> | The x-coordinate of the arc's center. |
y | The y-coordinate of the arc's center. | |
radius | The arc's radius. | |
startAngle | The starting angle, in radians. | |
endAngle | The ending angle, in radians. | |
counterclockwise | (Optional) Specifies whether the arc is drawn counterclockwise (true) or clockwise (false). Defaults to false. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcTo (...x1, y1, x2, y2, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:275
Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line if necessary.
Name | Type | Description |
---|---|---|
x1 | Parameters<GraphicsContext["arcTo"]> | The x-coordinate of the first control point. |
y1 | The y-coordinate of the first control point. | |
x2 | The x-coordinate of the second control point. | |
y2 | The y-coordinate of the second control point. | |
radius | The arc's radius. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcToSvg (...rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:290
Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
Name | Type | Description |
---|---|---|
rx | Parameters<GraphicsContext["arcToSvg"]> | The x-radius of the ellipse. |
ry | The y-radius of the ellipse. | |
xAxisRotation | The rotation of the ellipse's x-axis relative to the x-axis of the coordinate system, in degrees. | |
largeArcFlag | Determines if the arc should be greater than or less than 180 degrees. | |
sweepFlag | Determines if the arc should be swept in a positive angle direction. | |
x | The x-coordinate of the arc's end point. | |
y | The y-coordinate of the arc's end point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
beginFill (color, alpha)Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:744
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
beginPath () thisinherited
See scene_graphics_shared_Graphics.ts.html:240
Resets the current path. Any previous path and its commands are discarded and a new path is started. This is typically called before beginning a new shape or series of drawing commands.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
bezierCurveTo (...cp1x, cp1y, cp2x, cp2y, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:309
Adds a cubic Bezier curve to the path. It requires three points: the first two are control points and the third one is the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cp1x | Parameters<GraphicsContext["bezierCurveTo"]> | The x-coordinate of the first control point. |
cp1y | The y-coordinate of the first control point. | |
cp2x | The x-coordinate of the second control point. | |
cp2y | The y-coordinate of the second control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
chamferRect (...x, y, width, height, chamfer, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:517
Draw Rectangle with chamfer corners. These are angled corners.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["chamferRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
chamfer | non-zero real number, size of corner cutout | |
transform |
Type | Description |
---|---|
this |
circle (...x, y, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:352
Draws a circle shape. This method adds a new circle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["circle"]> | The x-coordinate of the center of the circle. |
y | The y-coordinate of the center of the circle. | |
radius | The radius of the circle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
clear () thisinherited
See scene_graphics_shared_Graphics.ts.html:663
Clears all drawing commands from the graphics context, effectively resetting it. This includes clearing the path, and optionally resetting transformations to the identity matrix.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
See scene_graphics_shared_Graphics.ts.html:697
Creates a new Graphics object. Note that only the context of the object is cloned, not its transform (position,scale,etc)
Name | Type | Default | Description |
---|---|---|---|
deep | boolean | false | Whether to create a deep clone of the graphics object. If false, the context will be shared between the two objects (default false). If true, the context will be cloned (recommended if you need to modify the context in any way). |
Type | Description |
---|---|
Graphics |
|
closePath () thisinherited
See scene_graphics_shared_Graphics.ts.html:329
Closes the current path by drawing a straight line back to the start. If the shape is already closed or there are no points in the path, this method does nothing.
Type | Description |
---|---|
this | The instance of the current object for chaining. |
containsPoint (point)inherited
See scene_graphics_shared_Graphics.ts.html:120
Checks if the object contains the given point.
Name | Type | Description |
---|---|---|
point | PointData | The point to check |
cut () thisinherited
See scene_graphics_shared_Graphics.ts.html:249
Applies a cutout to the last drawn shape. This is used to create holes or complex shapes by subtracting a path from the previously drawn path. If a hole is not completely in a shape, it will fail to cut correctly!
Type | Description |
---|---|
this |
destroy (options) voidinherited
See scene_graphics_shared_Graphics.ts.html:129
Destroys this graphics renderable and optionally its context.
If the context was created by this graphics and destroy(false)
or destroy()
is called then the context will still be destroyed.
If you want to explicitly not destroy this context that this graphics created, then you should pass destroy({ context: false })
If the context was passed in as an argument to the constructor then it will not be destroyed
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
options | DestroyOptions | <optional> | Options parameter. A boolean will act as if all options | |
options.texture | boolean | <optional> | false | Should destroy the texture of the graphics context |
options.textureSource | boolean | <optional> | false | Should destroy the texture source of the graphics context |
options.context | boolean | <optional> | false | Should destroy the context |
drawCircle (...args) thisDeprecated`` : since 8.0.0 Use Graphics#circle insteadinherited
See scene_graphics_shared_Graphics.ts.html:790
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawEllipse (...args) thisDeprecated`` : since 8.0.0 Use Graphics#ellipse insteadinherited
See scene_graphics_shared_Graphics.ts.html:803
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawPolygon (...args) thisDeprecated`` : since 8.0.0 Use Graphics#poly insteadinherited
See scene_graphics_shared_Graphics.ts.html:816
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#rect insteadinherited
See scene_graphics_shared_Graphics.ts.html:829
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRoundedRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#roundRect insteadinherited
See scene_graphics_shared_Graphics.ts.html:842
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawStar (...args) thisDeprecated`` : since 8.0.0 Use Graphics#star insteadinherited
See scene_graphics_shared_Graphics.ts.html:855
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
ellipse (...x, y, radiusX, radiusY) thisinherited
See scene_graphics_shared_Graphics.ts.html:338
Draws an ellipse at the specified location and with the given x and y radii. An optional transformation can be applied, allowing for rotation, scaling, and translation.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["ellipse"]> | The x-coordinate of the center of the ellipse. |
y | The y-coordinate of the center of the ellipse. | |
radiusX | The horizontal radius of the ellipse. | |
radiusY | The vertical radius of the ellipse. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
endFill ()Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:767
fill (...style) thisinherited
See scene_graphics_shared_Graphics.ts.html:193
Fills the current or given path with the current fill style. This method can optionally take a color and alpha for a simple fill, or a more complex FillStyle object for advanced fills.
Name | Type | Description |
---|---|---|
style | FillInput | (Optional) The style to fill the path with. Can be a color, gradient, pattern, or a complex style object. If omitted, uses the current fill style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
fill (color, alpha) thisDeprecated`` : 8.0.0inherited
See scene_graphics_shared_Graphics.ts.html:201
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
Type | Description |
---|---|
this |
filletRect (...x, y, width, height, fillet) thisinherited
See scene_graphics_shared_Graphics.ts.html:503
Draw Rectangle with fillet corners. This is much like rounded rectangle however it support negative numbers as well for the corner radius.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["filletRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
fillet | accept negative or positive values |
Type | Description |
---|---|
this |
See scene_graphics_shared_Graphics.ts.html:576
Returns the current transformation matrix of the graphics context.
Type | Description |
---|---|
Matrix | The current transformation matrix. |
lineStyle (width, color, alpha) thisDeprecated`` : since 8.0.0 Use Graphics#setStrokeStyle insteadinherited
See scene_graphics_shared_Graphics.ts.html:720
Name | Type | Attributes | Description |
---|---|---|---|
width | number | <optional> | |
color | ColorSource | <optional> | |
alpha | number | <optional> |
Type | Description |
---|---|
this |
lineTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:374
Connects the current point to a new point with a straight line. This method updates the current path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["lineTo"]> | The x-coordinate of the new point to connect to. |
y | The y-coordinate of the new point to connect to. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
moveTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:385
Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["moveTo"]> | The x-coordinate for the starting point. |
y | The y-coordinate for the starting point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
path (...path) thisinherited
See scene_graphics_shared_Graphics.ts.html:364
Adds another GraphicsPath
to this path, optionally applying a transformation.
Name | Type | Description |
---|---|---|
path | Parameters<GraphicsContext["path"]> | The GraphicsPath to add. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
poly (...points, close) thisinherited
See scene_graphics_shared_Graphics.ts.html:440
Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons, which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled, rotated, or translated as needed.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["poly"]> | An array of numbers, or an array of PointData objects eg [{x,y}, {x,y}, {x,y}] representing the x and y coordinates, of the polygon's vertices, in sequence. |
close | A boolean indicating whether to close the polygon path. True by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
quadraticCurveTo (...cpx, cpy, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:396
Adds a quadratic curve to the path. It requires two points: the control point and the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cpx | Parameters<GraphicsContext["quadraticCurveTo"]> | The x-coordinate of the control point. |
cpy | The y-coordinate of the control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
rect (...x, y, w, h) thisinherited
See scene_graphics_shared_Graphics.ts.html:411
Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["rect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
regularPoly (...x, y, radius, sides, rotation, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:454
Draws a regular polygon with a specified number of sides. All sides and angles are equal.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["regularPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. | |
transform | An optional Matrix object to apply a transformation to the polygon. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
resetTransform () thisinherited
See scene_graphics_shared_Graphics.ts.html:584
Resets the current transformation matrix to the identity matrix, effectively removing any transformations (rotation, scaling, translation) previously applied.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
restore (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:562
Restores the most recently saved graphics state by popping the top of the graphics state stack. This includes transformations, fill styles, and stroke styles.
Name | Type | Description |
---|---|---|
args | Parameters<GraphicsContext["restore"]> |
Type | Description |
---|---|
this |
rotateTransform (...angle) thisinherited
See scene_graphics_shared_Graphics.ts.html:593
Applies a rotation transformation to the graphics context around the current origin.
Name | Type | Description |
---|---|---|
angle | Parameters<GraphicsContext["rotate"]> | The angle of rotation in radians. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
roundPoly (...x, y, radius, sides, corner, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:469
Draws a polygon with rounded corners. Similar to regularPoly
but with the ability to round the corners of the polygon.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
corner | The radius of the rounding of the corners. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundRect (...x, y, w, h, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:424
Draws a rectangle with rounded corners. The corner radius can be specified to determine how rounded the corners should be. An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundRect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. | |
radius | The radius of the rectangle's corners. If not specified, corners will be sharp. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundShape (...points, radius, useQuadratic, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:485
Draws a shape with rounded corners. This function supports custom radius for each corner of the shape. Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["roundShape"]> | An array of RoundedPoint representing the corners of the shape to draw. A minimum of 3 points is required. |
radius | The default radius for the corners. This radius is applied to all corners unless overridden in points . |
|
useQuadratic | If set to true, rounded corners are drawn using a quadraticCurve method instead of an arc method. Defaults to false. | |
smoothness | Specifies the smoothness of the curve when useQuadratic is true. Higher values make the curve smoother. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
save () thisinherited
See scene_graphics_shared_Graphics.ts.html:571
Saves the current graphics state, including transformations, fill styles, and stroke styles, onto a stack.
Type | Description |
---|---|
this |
scaleTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:603
Applies a scaling transformation to the graphics context, scaling drawings by x horizontally and by y vertically.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["scale"]> | The scale factor in the horizontal direction. |
y | (Optional) The scale factor in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setFillStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:169
Sets the current fill style of the graphics context. The fill style can be a color, gradient, pattern, or a more complex style defined by a FillStyle object.
Name | Type | Description |
---|---|---|
args | FillInput | The fill style to apply. This can be a simple color, a gradient or pattern object, or a FillStyle or ConvertedFillStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setStrokeStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:181
Sets the current stroke style of the graphics context. Similar to fill styles, stroke styles can encompass colors, gradients, patterns, or more detailed configurations via a StrokeStyle object.
Name | Type | Description |
---|---|---|
args | StrokeInput | The stroke style to apply. Can be defined as a color, a gradient or pattern, or a StrokeStyle or ConvertedStrokeStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setTransform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:615
Sets the current transformation matrix of the graphics context to the specified matrix or values. This replaces the current transformation matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
star (...x, y, points, radius, innerRadius, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:531
Draws a star shape centered at a specified location. This method allows for the creation of stars with a variable number of points, outer radius, optional inner radius, and rotation. The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points. An optional transformation can be applied to scale, rotate, or translate the star as needed.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["star"]> | The x-coordinate of the center of the star. |
y | The y-coordinate of the center of the star. | |
points | The number of points of the star. | |
radius | The outer radius of the star (distance from the center to the outer points). | |
innerRadius | Optional. The inner radius of the star (distance from the center to the inner points between the outer points). If not provided, defaults to half of the radius . |
|
rotation | Optional. The rotation of the star in radians, where 0 is aligned with the y-axis. Defaults to 0, meaning one point is directly upward. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
stroke (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:207
Strokes the current path with the current stroke style. This method can take an optional FillStyle parameter to define the stroke's appearance, including its color, width, and other properties.
Name | Type | Description |
---|---|---|
args | FillStyle | (Optional) The stroke style to apply. Can be defined as a simple color or a more complex style object. If omitted, uses the current stroke style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
svg (...svg) thisinherited
See scene_graphics_shared_Graphics.ts.html:552
Parses and renders an SVG string into the graphics context. This allows for complex shapes and paths defined in SVG format to be drawn within the graphics context.
Name | Type | Description |
---|---|---|
svg | Parameters<GraphicsContext["svg"]> | The SVG string to be parsed and rendered. |
Type | Description |
---|---|
this |
texture (...texture, tint, dx, dy, dw, dh) thisinherited
See scene_graphics_shared_Graphics.ts.html:218
Adds a texture to the graphics context. This method supports multiple overloads for specifying the texture, tint, and dimensions. If only a texture is provided, it uses the texture's width and height for drawing. Additional parameters allow for specifying a tint color, and custom dimensions for the texture drawing area.
Name | Type | Description |
---|---|---|
texture | [Texture, unknown, unknown, unknown, unknown, unknown] | The Texture object to use. |
tint | (Optional) A ColorSource to tint the texture. If not provided, defaults to white (0xFFFFFF). | |
dx | (Optional) The x-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dy | (Optional) The y-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dw | (Optional) The width of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame width. | |
dh | (Optional) The height of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame height. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
transform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:633
Applies the specified transformation matrix to the current graphics context by multiplying the current matrix with the specified matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
translateTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:651
Applies a translation transformation to the graphics context, moving the origin by the specified amounts.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["translate"]> | The amount to translate in the horizontal direction. |
y | (Optional) The amount to translate in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
From class Container
_getGlobalBoundsRecursive (factorRenderLayers, bounds, currentLayer) voidinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:31
Recursively calculates the global bounds for the container and its children. This method is used internally by getFastGlobalBounds to traverse the scene graph.
Name | Type | Description |
---|---|---|
factorRenderLayers | boolean | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | The bounds object to update with the calculated values. |
currentLayer | IRenderLayer | The current render layer being processed. |
addChild (...children) Containerinherited
See scene_container_Container.ts.html:630
Adds one or more children to the container.
Multiple items can be added like so: myContainer.addChild(thingOne, thingTwo, thingThree)
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to add to the container |
Type | Description |
---|---|
Container |
|
addChildAt (child, index) Containerinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:151
Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown. If the child is already in this container, it will be moved to the specified index.
Name | Type | Description |
---|---|---|
child | Container | The child to add. |
index | number | The absolute index where the child will be positioned at the end of the operation. |
Type | Description |
---|---|
Container | The child that was added. |
addEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:681
Unlike on
or addListener
which are methods from EventEmitter, addEventListener
seeks to be compatible with the DOM's addEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event to listen to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | AddListenerOptions | <optional> | Listener options, used for capture phase. |
// Tell the user whether they did a single, double, triple, or nth click.
button.addEventListener('click', {
handleEvent(e): {
let prefix;
switch (e.detail) {
case 1: prefix = 'single'; break;
case 2: prefix = 'double'; break;
case 3: prefix = 'triple'; break;
default: prefix = e.detail + 'th'; break;
}
console.log('That was a ' + prefix + 'click');
}
});
// But skip the first click!
button.parent.addEventListener('click', function blockClickOnce(e) {
e.stopImmediatePropagation();
button.parent.removeEventListener('click', blockClickOnce, true);
}, {
capture: true,
});
cacheAsTexture (val) voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:13
Caches this container as a texture. This allows the container to be rendered as a single texture, which can improve performance for complex static containers.
Name | Type | Description |
---|---|---|
val | boolean | CacheAsTextureOptions | If true, enables caching with default options. If false, disables caching. Can also pass options object to configure caching behavior. |
collectRenderables (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:15
Collects all renderables from the container and its children, adding them to the instruction set. This method decides whether to use a simple or advanced collection method based on the container's properties.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesSimple (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:25
Collects renderables using a simple method, suitable for containers marked as simple. This method iterates over the container's children and adds their renderables to the instruction set.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesWithEffects (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:35
Collects renderables using an advanced method, suitable for containers with complex processing needs. This method handles additional effects and transformations that may be applied to the renderables.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
disableRenderGroup () voidinherited
See scene_container_Container.ts.html:831
This will disable the render group for this container.
dispatchEvent (e) booleaninherited
See events_FederatedEventTarget.ts.html:772
Dispatch the event on this Container using the event's EventBoundary.
The target of the event is set to this
and the defaultPrevented
flag is cleared before dispatch.
Name | Type | Description |
---|---|---|
e | Event | The event to dispatch. |
Type | Description |
---|---|
boolean | Whether the preventDefault() method was not invoked. |
// Reuse a click event!
button.dispatchEvent(clickEvent);
enableRenderGroup () voidinherited
See scene_container_Container.ts.html:807
Calling this enables a render group for this container. This means it will be rendered as a separate set of instructions. The transform of the container will also be handled on the GPU rather than the CPU.
eventMode (value)inherited
See events_FederatedEventTarget.ts.html:601
Enable interaction events for the Container. Touch, pointer and mouse. There are 5 types of interaction settings:
'none'
: Ignores all interaction events, even on its children.'passive'
: (default) Does not emit events and ignores all hit testing on itself and non-interactive children. Interactive children will still emit events.'auto'
: Does not emit events but is hit tested if parent is interactive. Same asinteractive = false
in v7'static'
: Emit events and is hit tested. Same asinteraction = true
in v7'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
Name | Type | Description |
---|---|---|
value |
Since:
: - 7.2.0
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.on('tap', (event) => {
// Handle event
});
See scene_container_container-mixins_effectsMixin.ts.html:238
The area the filter is applied to. This is used as more of an optimization rather than figuring out the dimensions of the displayObject each frame you can set this rectangle.
Also works as an interaction mask.
Type | Description |
---|---|
Rectangle |
filters () readonlyinherited
See scene_container_container-mixins_effectsMixin.ts.html:191
Sets the filters for the displayObject. IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. To remove filters simply set this property to 'null'
.
Type | Description |
---|---|
readonly |
See scene_container_container-mixins_measureMixin.ts.html:111
Calculates and returns the (world) bounds of the display object as a Rectangle.
Name | Type | Attributes | Description |
---|---|---|---|
skipUpdate | boolean | <optional> | Setting to true will stop the transforms of the scene graph from being updated. This means the calculation returned MAY be out of date BUT will give you a nice performance boost. |
bounds | Bounds | <optional> | Optional bounds to store the result of the bounds calculation. |
Type | Description |
---|---|
Bounds |
|
getChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:100
Returns the child at the specified index
Name | Type | Description |
---|---|---|
index | number | The index to get the child at |
Type | Description |
---|---|
U |
|
getChildByLabel (label, deep) Containerinherited
See scene_container_container-mixins_findMixin.ts.html:66
Returns the first child in the container with the specified label.
Recursive searches are done in a pre-order traversal.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
Type | Description |
---|---|
Container | The child with the specified label. |
getChildByName (name, deep) ContainerDeprecated`` : since 8.0.0inherited
See scene_container_container-mixins_findMixin.ts.html:53
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
name | string | Instance name. | ||
deep | boolean | <optional> | false | Whether to search recursively |
See: getChildByLabel
Type | Description |
---|---|
Container | The child with the specified name. |
getChildIndex (child) numberinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:133
Returns the index position of a child Container instance
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The Container instance to identify |
Type | Description |
---|---|
number |
|
getChildrenByLabel (label, deep, out) Array<Container>inherited
See scene_container_container-mixins_findMixin.ts.html:103
Returns all children in the container with the specified label.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
out | Array<Container> | <optional> | [] | The array to store matching children in. |
Type | Description |
---|---|
Array<Container> | An array of children with the specified label. |
getFastGlobalBounds (factorRenderLayers, bounds) Boundsinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:17
Computes an approximate global bounding box for the container and its children. This method is optimized for speed by using axis-aligned bounding boxes (AABBs), and uses the last render results from when it updated the transforms. This function does not update them. which may result in slightly larger bounds but never smaller than the actual bounds.
for accurate (but less performant) results use container.getGlobalBounds
Name | Type | Attributes | Description |
---|---|---|---|
factorRenderLayers | boolean | <optional> | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | <optional> | The output bounds object to store the result. If not provided, a new one is created. |
Type | Description |
---|---|
Bounds | The computed bounds. |
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:15
Returns the global position of the container.
Name | Type | Default | Description |
---|---|---|---|
point | Point | The optional point to write the global value to. | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
Point |
|
See scene_container_container-mixins_measureMixin.ts.html:73
Retrieves the local bounds of the container as a Bounds object.
Type | Description |
---|---|
Bounds |
|
See scene_container_Container.ts.html:1059
Retrieves the size of the container as a Size object. This is faster than get the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
out | Size | <optional> | Optional object to store the size in. |
Type | Description |
---|---|
Size |
|
interactive (value)inherited
See events_FederatedEventTarget.ts.html:585
Enable interaction events for the Container. Touch, pointer and mouse
Name | Type | Description |
---|---|---|
value | boolean |
isCachedAsTexture () booleaninherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:46
Is this container cached as a texture?
Type | Description |
---|---|
boolean |
isInteractive () booleaninherited
See events_FederatedEventTarget.ts.html:631
Determines if the container is interactive or not
Since:
: - 7.2.0
Type | Description |
---|---|
boolean | Whether the container is interactive or not |
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.isInteractive(); // true
sprite.eventMode = 'dynamic';
sprite.isInteractive(); // true
sprite.eventMode = 'none';
sprite.isInteractive(); // false
sprite.eventMode = 'passive';
sprite.isInteractive(); // false
sprite.eventMode = 'auto';
sprite.isInteractive(); // false
mask () unknowninherited
See scene_container_container-mixins_effectsMixin.ts.html:110
Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. In PixiJS a regular mask must be a Graphics or a {@link Sprite} object. This allows for much faster masking in canvas as it utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. Otherwise, getLocalBounds
may calculate incorrect bounds, which makes the container's width and height wrong. To remove a mask, set this property to null
.
For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
Type | Description |
---|---|
unknown |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.mask = graphics;
See scene_container_container-mixins_onRenderMixin.ts.html:16
This callback is used when the container is rendered. This is where you should add your custom logic that is needed to be run every frame.
In v7 many users used updateTransform
for this, however the way v8 renders objects is different and "updateTransform" is no longer called every frame
Type | Description |
---|---|
(renderer: Renderer) => void |
const container = new Container();
container.onRender = () => {
container.rotation += 0.01;
};
removeChild (...children) Containerinherited
See scene_container_Container.ts.html:709
Removes one or more children from the container.
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to remove |
Type | Description |
---|---|
Container | The first child that was removed. |
removeChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:87
Removes a child from the specified index position.
Name | Type | Description |
---|---|---|
index | number | The index to get the child from |
Type | Description |
---|---|
U | The child that was removed. |
removeChildren (beginIndex, endIndex) ContainerChild[]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:29
Removes all children from this container that are within the begin and end indexes.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
beginIndex | number | 0 | The beginning position. | |
endIndex | number | <optional> | The ending position. Default value is size of the container. |
Type | Description |
---|---|
ContainerChild[] |
|
removeEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:748
Unlike off
or removeListener
which are methods from EventEmitter, removeEventListener
seeks to be compatible with the DOM's removeEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event the listener is bound to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | RemoveListenerOptions | <optional> | The original listener options. This is required to deregister a capture phase listener. |
removeFromParent ()inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:249
Remove the Container from its parent Container. If the Container has no parent, do nothing.
reparentChild (...child) U[0]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:258
Reparent the child to this container, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
Type | Description |
---|---|
U[0] | The first child that was reparented. |
reparentChildAt (child, index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:276
Reparent the child to this container at the specified index, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
index | number | The index to reparent the child to |
Type | Description |
---|---|
U |
setChildIndex (child, index) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:116
Changes the position of an existing child in the container
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The child Container instance for which you want to change the index number |
index | number | The resulting index number for the child container |
setFromMatrix (matrix) voidinherited
See scene_container_Container.ts.html:1154
Updates the local transform using the given matrix.
Name | Type | Description |
---|---|---|
matrix | Matrix | The matrix to use for updating the transform. |
setMask (options)inherited
See scene_container_container-mixins_effectsMixin.ts.html:132
Used to set mask and control mask options.
Name | Type | Description |
---|---|---|
options | Partial<MaskOptionsAndMask> |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.setMask({
mask: graphics,
inverse: true,
});
setSize (value, height)inherited
See scene_container_Container.ts.html:1081
Sets the size of the container to the specified width and height. This is faster than setting the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
value | number | Optional<Size, "height"> | This can be either a number or a Size object. | |
height | number | <optional> | The height to set. Defaults to the value of width if not provided. |
swapChildren (child, child2) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:221
Swaps the position of 2 Containers within this container.
Name | Type | Description |
---|---|---|
child | U | First container to swap |
child2 | U | Second container to swap |
toGlobal (position, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:37
Calculates the global position of the container.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
position | PointData | The world origin to calculate from. | ||
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
P |
|
toLocal (position, from, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:58
Calculates the local position of the container relative to another point.
Name | Type | Attributes | Description |
---|---|---|---|
position | PointData | The world origin to calculate from. | |
from | Container | <optional> | The Container to calculate the global position from. |
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). |
skipUpdate | boolean | <optional> | Should we skip the update transform |
Type | Description |
---|---|
P |
|
updateCacheTexture () voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:70
Updates the cached texture. Will flag that this container's cached texture needs to be redrawn. This will happen on the next render.
updateLocalTransform () voidinherited
See scene_container_Container.ts.html:1163
Updates the local transform.
updateTransform (opts) thisinherited
See scene_container_Container.ts.html:1118
Updates the transform properties of the container (accepts partial values).
Name | Type | Description |
---|---|---|
opts | object | The options for updating the transform. |
opts.x | number | The x position of the container. |
opts.y | number | The y position of the container. |
opts.scaleX | number | The scale factor on the x-axis. |
opts.scaleY | number | The scale factor on the y-axis. |
opts.rotation | number | The rotation of the container, in radians. |
opts.skewX | number | The skew factor on the x-axis. |
opts.skewY | number | The skew factor on the y-axis. |
opts.pivotX | number | The x coordinate of the pivot point. |
opts.pivotY | number | The y coordinate of the pivot point. |
Type | Description |
---|---|
this |
zIndex (value)inherited
See scene_container_container-mixins_sortMixin.ts.html:42
The zIndex of the container.
Setting this value, will automatically set the parent to be sortable. Children will be automatically sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, and thus rendered on top of other display objects within the same container.
Name | Type | Description |
---|---|---|
value | number |
See: sortableChildren
From class Container
click inherited
See events_EventBoundaryTypes.ts.html:120
Fired when a pointer device button (usually a mouse left-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
A click
event fires after the pointerdown
and pointerup
events, in that order. If the mouse is moved over another Container after the pointerdown
event, the click
event is fired on the most specific common ancestor of the two target Containers.
The detail
property of the event is the number of clicks that occurred within a 200ms window of each other upto the current click. For example, it will be 2
for a double click.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
clickcapture inherited
See events_EventBoundaryTypes.ts.html:136
Capture phase equivalent of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalmousemove inherited
See events_EventBoundaryTypes.ts.html:206
Fired when a pointer device (usually a mouse) is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalpointermove inherited
See events_EventBoundaryTypes.ts.html:391
Fired when a pointer device is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globaltouchmove inherited
See events_EventBoundaryTypes.ts.html:571
Fired when a touch point is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousedown inherited
See events_EventBoundaryTypes.ts.html:52
Fired when a mouse button (usually a mouse left-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The mousedown event. |
mousedowncapture inherited
See events_EventBoundaryTypes.ts.html:61
Capture phase equivalent of mousedown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The capture phase mousedown. |
mouseenter inherited
See events_EventBoundaryTypes.ts.html:249
Fired when the mouse pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseentercapture inherited
See events_EventBoundaryTypes.ts.html:257
Capture phase equivalent of mouseenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseleave inherited
See events_EventBoundaryTypes.ts.html:285
Fired when the mouse pointer exits a Container and its descendants.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent |
mouseleavecapture inherited
See events_EventBoundaryTypes.ts.html:293
Capture phase equivalent of mouseleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemove inherited
See events_EventBoundaryTypes.ts.html:215
Fired when a pointer device (usually a mouse) is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemovecapture inherited
See events_EventBoundaryTypes.ts.html:224
Capture phase equivalent of mousemove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseout inherited
See events_EventBoundaryTypes.ts.html:265
Fired when a pointer device (usually a mouse) is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This may be fired on a Container that was removed from the scene graph immediately after a mouseover
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseoutcapture inherited
See events_EventBoundaryTypes.ts.html:277
Capture phase equivalent of mouseout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseover inherited
See events_EventBoundaryTypes.ts.html:232
Fired when a pointer device (usually a mouse) is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseovercapture inherited
See events_EventBoundaryTypes.ts.html:241
Capture phase equivalent of mouseover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseup inherited
See events_EventBoundaryTypes.ts.html:86
Fired when a pointer device button (usually a mouse left-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupcapture inherited
See events_EventBoundaryTypes.ts.html:95
Capture phase equivalent of mouseup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutside inherited
See events_EventBoundaryTypes.ts.html:164
Fired when a pointer device button (usually a mouse left-button) is released outside the container that initially registered a mousedown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:179
Capture phase equivalent of mouseupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancel inherited
See events_EventBoundaryTypes.ts.html:335
Fired when the operating system cancels a pointer event. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancelcapture inherited
See events_EventBoundaryTypes.ts.html:344
Capture phase equivalent of pointercancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdown inherited
See events_EventBoundaryTypes.ts.html:301
Fired when a pointer device button is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdowncapture inherited
See events_EventBoundaryTypes.ts.html:310
Capture phase equivalent of pointerdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerenter inherited
See events_EventBoundaryTypes.ts.html:434
Fired when the pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerentercapture inherited
See events_EventBoundaryTypes.ts.html:442
Capture phase equivalent of pointerenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerleave inherited
See events_EventBoundaryTypes.ts.html:467
Fired when the pointer leaves the hit testing boundaries of a Container and its descendants.
This event notifies only the target and does not bubble.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The pointerleave event. |
pointerleavecapture inherited
See events_EventBoundaryTypes.ts.html:477
Capture phase equivalent of pointerleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermove inherited
See events_EventBoundaryTypes.ts.html:400
Fired when a pointer device is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermovecapture inherited
See events_EventBoundaryTypes.ts.html:409
Capture phase equivalent of pointermove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerout inherited
See events_EventBoundaryTypes.ts.html:450
Fired when a pointer device is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointeroutcapture inherited
See events_EventBoundaryTypes.ts.html:459
Capture phase equivalent of pointerout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerover inherited
See events_EventBoundaryTypes.ts.html:417
Fired when a pointer device is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerovercapture inherited
See events_EventBoundaryTypes.ts.html:426
Capture phase equivalent of pointerover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertap inherited
See events_EventBoundaryTypes.ts.html:352
Fired when a pointer device button is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertapcapture inherited
See events_EventBoundaryTypes.ts.html:361
Capture phase equivalent of pointertap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerup inherited
See events_EventBoundaryTypes.ts.html:318
Fired when a pointer device button is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupcapture inherited
See events_EventBoundaryTypes.ts.html:327
Capture phase equivalent of pointerup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutside inherited
See events_EventBoundaryTypes.ts.html:369
Fired when a pointer device button is released outside the container that initially registered a pointerdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:383
Capture phase equivalent of pointerupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclick inherited
See events_EventBoundaryTypes.ts.html:144
Fired when a pointer device secondary button (usually a mouse right-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event follows the semantics of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclickcapture inherited
See events_EventBoundaryTypes.ts.html:156
Capture phase equivalent of rightclick
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdown inherited
See events_EventBoundaryTypes.ts.html:69
Fired when a pointer device secondary button (usually a mouse right-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdowncapture inherited
See events_EventBoundaryTypes.ts.html:78
Capture phase equivalent of rightdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The rightdowncapture event. |
rightup inherited
See events_EventBoundaryTypes.ts.html:103
Fired when a pointer device secondary button (usually a mouse right-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupcapture inherited
See events_EventBoundaryTypes.ts.html:112
Capture phase equivalent of rightup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutside inherited
See events_EventBoundaryTypes.ts.html:187
Fired when a pointer device secondary button (usually a mouse right-button) is released outside the container that initially registered a rightdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:198
Capture phase equivalent of rightupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tap inherited
See events_EventBoundaryTypes.ts.html:536
Fired when a touch point is placed and removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tapcapture inherited
See events_EventBoundaryTypes.ts.html:545
Capture phase equivalent of tap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancel inherited
See events_EventBoundaryTypes.ts.html:519
Fired when the operating system cancels a touch. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancelcapture inherited
See events_EventBoundaryTypes.ts.html:528
Capture phase equivalent of touchcancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchend inherited
See events_EventBoundaryTypes.ts.html:502
Fired when a touch point is removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendcapture inherited
See events_EventBoundaryTypes.ts.html:511
Capture phase equivalent of touchend
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutside inherited
See events_EventBoundaryTypes.ts.html:553
Fired when a touch point is removed outside of the container that initially registered a touchstart. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:563
Capture phase equivalent of touchendoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmove inherited
See events_EventBoundaryTypes.ts.html:580
Fired when a touch point is moved along the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmovecapture inherited
See events_EventBoundaryTypes.ts.html:589
Capture phase equivalent of touchmove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstart inherited
See events_EventBoundaryTypes.ts.html:485
Fired when a touch point is placed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstartcapture inherited
See events_EventBoundaryTypes.ts.html:494
Capture phase equivalent of touchstart
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
wheel inherited
See events_EventBoundaryTypes.ts.html:597
Fired when a the user scrolls with the mouse cursor over a Container.
These events are propagating from the EventSystem.
- FederatedWheelEvent
wheelcapture inherited
See events_EventBoundaryTypes.ts.html:605
Capture phase equivalent of wheel
.
These events are propagating from the EventSystem.
- FederatedWheelEvent
From class Graphics
The local bounds of the graphic.
fillStyleConvertedFillStyleinherited
The fill style to use.
strokeStyleConvertedStrokeStyleinherited
The stroke style to use.
The local bounds of the graphic.
fillStyleConvertedFillStyleinherited
The fill style to use.
strokeStyleConvertedStrokeStyleinherited
The stroke style to use.
From class Container
accessiblebooleaninherited
Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set
Default Value:
: - false
accessibleChildrenbooleaninherited
Setting to false will prevent any children inside this container to be accessible. Defaults to true.
Default Value:
: - true
accessibleHintstringinherited
Sets the aria-label attribute of the shadow div
Default Value:
: - undefined
accessiblePointerEventsPointerEventsinherited
Specify the pointer-events the accessible div will use Defaults to auto.
Default Value:
: - 'auto'
accessibleTextstringinherited
Sets the text content of the shadow div
Default Value:
: - undefined
accessibleTitlestringinherited
Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]'
Default Value:
: - undefined
accessibleTypestringinherited
Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button.
Default Value:
: - 'button'
alphanumberinherited
The opacity of the object.
anglenumberinherited
The angle of the object in degrees. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
blendModeBLEND_MODESinherited
The blend mode to be applied to the sprite. Apply a value of 'normal'
to reset the blend mode.
Default Value:
: - 'normal'
An optional bounds area for this container. Setting this rectangle will stop the renderer from recursively measuring the bounds of each children and instead use this single boundArea. This is great for optimisation! If for example you have a 1000 spinning particles and you know they all sit within a specific bounds, then setting it will mean the renderer will not need to measure the 1000 children to find the bounds. Instead it will just use the bounds you set.
cacheAsBitmapbooleanDeprecated : Since PixiJS v8inherited
Legacy property for backwards compatibility with PixiJS v7 and below. Use cacheAsTexture
instead.
childrenC[]readonlyinherited
The array of children of this container.
cullablebooleaninherited
Should this object be rendered if the bounds of this object are out of frame?
Culling has no effect on whether updateTransform is called.
Default Value:
: - false
cullableChildrenbooleaninherited
Determines if the children to the container can be culled Setting this to false allows PixiJS to bypass a recursive culling function Which can help to optimize very complex scenes
Default Value:
: - true
If set, this shape is used for culling instead of the bounds of this object. It can improve the culling performance of objects with many children. The culling area is defined in local space.
destroyedbooleaninherited
If the object has been destroyed via destroy(). If true, it should not be used.
Default Value:
: - false
effectsArray<Effect>inherited
TODO
: - Needs docs.
The group transform is a transform relative to the render group it belongs too. If this container is render group then this will be an identity matrix. other wise it will be the same as the relativeGroupTransform. Use this value when actually rendering things to the screen
heightnumberinherited
The height of the Container, setting this will actually modify the scale to achieve the value set.
hitAreaIHitAreainherited
Interaction shape. Children will be hit first, then this shape will be checked. Setting this will cause this shape to be checked in hit tests rather than the container's bounds.
Default Value:
: - undefined
import { Rectangle, Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.interactive = true;
sprite.hitArea = new Rectangle(0, 0, 100, 100);
interactiveChildrenbooleaninherited
Determines if the children to the container can be clicked/touched Setting this to false allows PixiJS to bypass a recursive hitTest
function
Default Value:
: - true
isCachedAsTexturebooleanreadonlyinherited
Whether this container is currently cached as a texture.
isRenderablebooleaninherited
Whether or not the object should be rendered.
isRenderGroupbooleaninherited
Returns true if this container is a render group. This means that it will be rendered as a separate pass, with its own set of instructions
labelstringinherited
The instance label of the object.
Default Value:
: - undefined
Current transform of the object based on local factors: position, scale, other stuff.
namestringDeprecated : since 8.0.0inherited
The instance name of the object.
See: label
onclickinherited
Property-based event handler for the click
event.
Default Value:
: - null
this.onclick = (event) => {
//some function here that happens on click
}
onglobalmousemoveinherited
Property-based event handler for the globalmousemove
event.
Default Value:
: - null
this.onglobalmousemove = (event) => {
//some function here that happens on globalmousemove
}
onglobalpointermoveinherited
Property-based event handler for the globalpointermove
event.
Default Value:
: - null
this.onglobalpointermove = (event) => {
//some function here that happens on globalpointermove
}
onglobaltouchmoveinherited
Property-based event handler for the globaltouchmove
event.
Default Value:
: - null
this.onglobaltouchmove = (event) => {
//some function here that happens on globaltouchmove
}
onmousedowninherited
Property-based event handler for the mousedown
event.
Default Value:
: - null
this.onmousedown = (event) => {
//some function here that happens on mousedown
}
onmouseenterinherited
Property-based event handler for the mouseenter
event.
Default Value:
: - null
this.onmouseenter = (event) => {
//some function here that happens on mouseenter
}
onmouseleaveinherited
Property-based event handler for the mouseleave
event.
Default Value:
: - null
this.onmouseleave = (event) => {
//some function here that happens on mouseleave
}
onmousemoveinherited
Property-based event handler for the mousemove
event.
Default Value:
: - null
this.onmousemove = (event) => {
//some function here that happens on mousemove
}
onmouseoutinherited
Property-based event handler for the mouseout
event.
Default Value:
: - null
this.onmouseout = (event) => {
//some function here that happens on mouseout
}
onmouseoverinherited
Property-based event handler for the mouseover
event.
Default Value:
: - null
this.onmouseover = (event) => {
//some function here that happens on mouseover
}
onmouseupinherited
Property-based event handler for the mouseup
event.
Default Value:
: - null
this.onmouseup = (event) => {
//some function here that happens on mouseup
}
onmouseupoutsideinherited
Property-based event handler for the mouseupoutside
event.
Default Value:
: - null
this.onmouseupoutside = (event) => {
//some function here that happens on mouseupoutside
}
onpointercancelinherited
Property-based event handler for the pointercancel
event.
Default Value:
: - null
this.onpointercancel = (event) => {
//some function here that happens on pointercancel
}
onpointerdowninherited
Property-based event handler for the pointerdown
event.
Default Value:
: - null
this.onpointerdown = (event) => {
//some function here that happens on pointerdown
}
onpointerenterinherited
Property-based event handler for the pointerenter
event.
Default Value:
: - null
this.onpointerenter = (event) => {
//some function here that happens on pointerenter
}
onpointerleaveinherited
Property-based event handler for the pointerleave
event.
Default Value:
: - null
this.onpointerleave = (event) => {
//some function here that happens on pointerleave
}
onpointermoveinherited
Property-based event handler for the pointermove
event.
Default Value:
: - null
this.onpointermove = (event) => {
//some function here that happens on pointermove
}
onpointeroutinherited
Property-based event handler for the pointerout
event.
Default Value:
: - null
this.onpointerout = (event) => {
//some function here that happens on pointerout
}
onpointeroverinherited
Property-based event handler for the pointerover
event.
Default Value:
: - null
this.onpointerover = (event) => {
//some function here that happens on pointerover
}
onpointertapinherited
Property-based event handler for the pointertap
event.
Default Value:
: - null
this.onpointertap = (event) => {
//some function here that happens on pointertap
}
onpointerupinherited
Property-based event handler for the pointerup
event.
Default Value:
: - null
this.onpointerup = (event) => {
//some function here that happens on pointerup
}
onpointerupoutsideinherited
Property-based event handler for the pointerupoutside
event.
Default Value:
: - null
this.onpointerupoutside = (event) => {
//some function here that happens on pointerupoutside
}
onrightclickinherited
Property-based event handler for the rightclick
event.
Default Value:
: - null
this.onrightclick = (event) => {
//some function here that happens on rightclick
}
onrightdowninherited
Property-based event handler for the rightdown
event.
Default Value:
: - null
this.onrightdown = (event) => {
//some function here that happens on rightdown
}
onrightupinherited
Property-based event handler for the rightup
event.
Default Value:
: - null
this.onrightup = (event) => {
//some function here that happens on rightup
}
onrightupoutsideinherited
Property-based event handler for the rightupoutside
event.
Default Value:
: - null
this.onrightupoutside = (event) => {
//some function here that happens on rightupoutside
}
ontapinherited
Property-based event handler for the tap
event.
Default Value:
: - null
this.ontap = (event) => {
//some function here that happens on tap
}
ontouchcancelinherited
Property-based event handler for the touchcancel
event.
Default Value:
: - null
this.ontouchcancel = (event) => {
//some function here that happens on touchcancel
}
ontouchendinherited
Property-based event handler for the touchend
event.
Default Value:
: - null
this.ontouchend = (event) => {
//some function here that happens on touchend
}
ontouchendoutsideinherited
Property-based event handler for the touchendoutside
event.
Default Value:
: - null
this.ontouchendoutside = (event) => {
//some function here that happens on touchendoutside
}
ontouchmoveinherited
Property-based event handler for the touchmove
event.
Default Value:
: - null
this.ontouchmove = (event) => {
//some function here that happens on touchmove
}
ontouchstartinherited
Property-based event handler for the touchstart
event.
Default Value:
: - null
this.ontouchstart = (event) => {
//some function here that happens on touchstart
}
onwheelinherited
Property-based event handler for the wheel
event.
Default Value:
: - null
this.onwheel = (event) => {
//some function here that happens on wheel
}
The display object container that contains this display object.
Default Value:
: - undefined
parentRenderLayerIRenderLayerreadonlyinherited
The RenderLayer this container belongs to, if any. If it belongs to a RenderLayer, it will be rendered from the RenderLayer's position in the scene.
The center of rotation, scaling, and skewing for this display object in its local space. The position
is the projection of pivot
in the parent's local space.
By default, the pivot is the origin (0, 0).
Since:
: - 4.0.0
positionObservablePointinherited
The coordinate of the object relative to the local coordinates of the parent.
Since:
: - 4.0.0
The relative group transform is a transform relative to the render group it belongs too. It will include all parent transforms and up to the render group (think of it as kind of like a stage - but the stage can be nested). If this container is is self a render group matrix will be relative to its parent render group
renderableinherited
Can this object be rendered, if false the object will not be drawn but the transform will still be updated.
rotationnumberinherited
The rotation of the object in radians. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
The scale factors of this object along the local coordinate axes.
The default scale is (1, 1).
Since:
: - 4.0.0
The skew factor for the object in radians.
Since:
: - 4.0.0
sortableChildrenbooleaninherited
If set to true, the container will sort its children by zIndex
value when the next render is called, or manually if sortChildren()
is called.
This actually changes the order of elements in the array, so should be treated as a basic solution that is not performant compared to other solutions, such as PixiJS Layers
Also be aware of that this may not work nicely with the addChildAt()
function, as the zIndex
sorting may cause the child to automatically sorted to another position.
Default Value:
: - false
sortDirtybooleaninherited
Should children be sorted by zIndex at the next render call.
Will get automatically set to true if a new child is added, or if a child's zIndex changes.
Default Value:
: - false
tabIndexnumberinherited
Default Value:
: - 0
TODO
: - Needs docs.
tintnumberinherited
The tint applied to the sprite. This is a hex value.
A value of 0xFFFFFF will remove any tint effect.
Default Value:
: - 0xFFFFFF
uidnumberreadonlyinherited
unique id for this container
updateCacheTexture() => voidinherited
Updates the cached texture of this container. This will flag the container's cached texture to be redrawn on the next render.
visibleinherited
The visibility of the object. If false the object will not be drawn, and the transform will not be updated.
widthnumberinherited
The width of the Container, setting this will actually modify the scale to achieve the value set.
worldTransformreadonlyinherited
Current transform of the object based on world (parent) factors.
xnumberinherited
The position of the container on the x axis relative to the local coordinates of the parent. An alias to position.x
ynumberinherited
The position of the container on the y axis relative to the local coordinates of the parent. An alias to position.y
accessiblebooleaninherited
Flag for if the object is accessible. If true AccessibilityManager will overlay a shadow div with attributes set
Default Value:
: - false
accessibleChildrenbooleaninherited
Setting to false will prevent any children inside this container to be accessible. Defaults to true.
Default Value:
: - true
accessibleHintstringinherited
Sets the aria-label attribute of the shadow div
Default Value:
: - undefined
accessiblePointerEventsPointerEventsinherited
Specify the pointer-events the accessible div will use Defaults to auto.
Default Value:
: - 'auto'
accessibleTextstringinherited
Sets the text content of the shadow div
Default Value:
: - undefined
accessibleTitlestringinherited
Sets the title attribute of the shadow div If accessibleTitle AND accessibleHint has not been this will default to 'container [tabIndex]'
Default Value:
: - undefined
accessibleTypestringinherited
Specify the type of div the accessible layer is. Screen readers treat the element differently depending on this type. Defaults to button.
Default Value:
: - 'button'
alphanumberinherited
The opacity of the object.
anglenumberinherited
The angle of the object in degrees. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
blendModeBLEND_MODESinherited
The blend mode to be applied to the sprite. Apply a value of 'normal'
to reset the blend mode.
Default Value:
: - 'normal'
An optional bounds area for this container. Setting this rectangle will stop the renderer from recursively measuring the bounds of each children and instead use this single boundArea. This is great for optimisation! If for example you have a 1000 spinning particles and you know they all sit within a specific bounds, then setting it will mean the renderer will not need to measure the 1000 children to find the bounds. Instead it will just use the bounds you set.
cacheAsBitmapbooleanDeprecated : Since PixiJS v8inherited
Legacy property for backwards compatibility with PixiJS v7 and below. Use cacheAsTexture
instead.
childrenC[]readonlyinherited
The array of children of this container.
cullablebooleaninherited
Should this object be rendered if the bounds of this object are out of frame?
Culling has no effect on whether updateTransform is called.
Default Value:
: - false
cullableChildrenbooleaninherited
Determines if the children to the container can be culled Setting this to false allows PixiJS to bypass a recursive culling function Which can help to optimize very complex scenes
Default Value:
: - true
If set, this shape is used for culling instead of the bounds of this object. It can improve the culling performance of objects with many children. The culling area is defined in local space.
destroyedbooleaninherited
If the object has been destroyed via destroy(). If true, it should not be used.
Default Value:
: - false
effectsArray<Effect>inherited
TODO
: - Needs docs.
The group transform is a transform relative to the render group it belongs too. If this container is render group then this will be an identity matrix. other wise it will be the same as the relativeGroupTransform. Use this value when actually rendering things to the screen
heightnumberinherited
The height of the Container, setting this will actually modify the scale to achieve the value set.
hitAreaIHitAreainherited
Interaction shape. Children will be hit first, then this shape will be checked. Setting this will cause this shape to be checked in hit tests rather than the container's bounds.
Default Value:
: - undefined
import { Rectangle, Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.interactive = true;
sprite.hitArea = new Rectangle(0, 0, 100, 100);
interactiveChildrenbooleaninherited
Determines if the children to the container can be clicked/touched Setting this to false allows PixiJS to bypass a recursive hitTest
function
Default Value:
: - true
isCachedAsTexturebooleanreadonlyinherited
Whether this container is currently cached as a texture.
isRenderablebooleaninherited
Whether or not the object should be rendered.
isRenderGroupbooleaninherited
Returns true if this container is a render group. This means that it will be rendered as a separate pass, with its own set of instructions
labelstringinherited
The instance label of the object.
Default Value:
: - undefined
Current transform of the object based on local factors: position, scale, other stuff.
namestringDeprecated : since 8.0.0inherited
The instance name of the object.
See: label
onclickinherited
Property-based event handler for the click
event.
Default Value:
: - null
this.onclick = (event) => {
//some function here that happens on click
}
onglobalmousemoveinherited
Property-based event handler for the globalmousemove
event.
Default Value:
: - null
this.onglobalmousemove = (event) => {
//some function here that happens on globalmousemove
}
onglobalpointermoveinherited
Property-based event handler for the globalpointermove
event.
Default Value:
: - null
this.onglobalpointermove = (event) => {
//some function here that happens on globalpointermove
}
onglobaltouchmoveinherited
Property-based event handler for the globaltouchmove
event.
Default Value:
: - null
this.onglobaltouchmove = (event) => {
//some function here that happens on globaltouchmove
}
onmousedowninherited
Property-based event handler for the mousedown
event.
Default Value:
: - null
this.onmousedown = (event) => {
//some function here that happens on mousedown
}
onmouseenterinherited
Property-based event handler for the mouseenter
event.
Default Value:
: - null
this.onmouseenter = (event) => {
//some function here that happens on mouseenter
}
onmouseleaveinherited
Property-based event handler for the mouseleave
event.
Default Value:
: - null
this.onmouseleave = (event) => {
//some function here that happens on mouseleave
}
onmousemoveinherited
Property-based event handler for the mousemove
event.
Default Value:
: - null
this.onmousemove = (event) => {
//some function here that happens on mousemove
}
onmouseoutinherited
Property-based event handler for the mouseout
event.
Default Value:
: - null
this.onmouseout = (event) => {
//some function here that happens on mouseout
}
onmouseoverinherited
Property-based event handler for the mouseover
event.
Default Value:
: - null
this.onmouseover = (event) => {
//some function here that happens on mouseover
}
onmouseupinherited
Property-based event handler for the mouseup
event.
Default Value:
: - null
this.onmouseup = (event) => {
//some function here that happens on mouseup
}
onmouseupoutsideinherited
Property-based event handler for the mouseupoutside
event.
Default Value:
: - null
this.onmouseupoutside = (event) => {
//some function here that happens on mouseupoutside
}
onpointercancelinherited
Property-based event handler for the pointercancel
event.
Default Value:
: - null
this.onpointercancel = (event) => {
//some function here that happens on pointercancel
}
onpointerdowninherited
Property-based event handler for the pointerdown
event.
Default Value:
: - null
this.onpointerdown = (event) => {
//some function here that happens on pointerdown
}
onpointerenterinherited
Property-based event handler for the pointerenter
event.
Default Value:
: - null
this.onpointerenter = (event) => {
//some function here that happens on pointerenter
}
onpointerleaveinherited
Property-based event handler for the pointerleave
event.
Default Value:
: - null
this.onpointerleave = (event) => {
//some function here that happens on pointerleave
}
onpointermoveinherited
Property-based event handler for the pointermove
event.
Default Value:
: - null
this.onpointermove = (event) => {
//some function here that happens on pointermove
}
onpointeroutinherited
Property-based event handler for the pointerout
event.
Default Value:
: - null
this.onpointerout = (event) => {
//some function here that happens on pointerout
}
onpointeroverinherited
Property-based event handler for the pointerover
event.
Default Value:
: - null
this.onpointerover = (event) => {
//some function here that happens on pointerover
}
onpointertapinherited
Property-based event handler for the pointertap
event.
Default Value:
: - null
this.onpointertap = (event) => {
//some function here that happens on pointertap
}
onpointerupinherited
Property-based event handler for the pointerup
event.
Default Value:
: - null
this.onpointerup = (event) => {
//some function here that happens on pointerup
}
onpointerupoutsideinherited
Property-based event handler for the pointerupoutside
event.
Default Value:
: - null
this.onpointerupoutside = (event) => {
//some function here that happens on pointerupoutside
}
onrightclickinherited
Property-based event handler for the rightclick
event.
Default Value:
: - null
this.onrightclick = (event) => {
//some function here that happens on rightclick
}
onrightdowninherited
Property-based event handler for the rightdown
event.
Default Value:
: - null
this.onrightdown = (event) => {
//some function here that happens on rightdown
}
onrightupinherited
Property-based event handler for the rightup
event.
Default Value:
: - null
this.onrightup = (event) => {
//some function here that happens on rightup
}
onrightupoutsideinherited
Property-based event handler for the rightupoutside
event.
Default Value:
: - null
this.onrightupoutside = (event) => {
//some function here that happens on rightupoutside
}
ontapinherited
Property-based event handler for the tap
event.
Default Value:
: - null
this.ontap = (event) => {
//some function here that happens on tap
}
ontouchcancelinherited
Property-based event handler for the touchcancel
event.
Default Value:
: - null
this.ontouchcancel = (event) => {
//some function here that happens on touchcancel
}
ontouchendinherited
Property-based event handler for the touchend
event.
Default Value:
: - null
this.ontouchend = (event) => {
//some function here that happens on touchend
}
ontouchendoutsideinherited
Property-based event handler for the touchendoutside
event.
Default Value:
: - null
this.ontouchendoutside = (event) => {
//some function here that happens on touchendoutside
}
ontouchmoveinherited
Property-based event handler for the touchmove
event.
Default Value:
: - null
this.ontouchmove = (event) => {
//some function here that happens on touchmove
}
ontouchstartinherited
Property-based event handler for the touchstart
event.
Default Value:
: - null
this.ontouchstart = (event) => {
//some function here that happens on touchstart
}
onwheelinherited
Property-based event handler for the wheel
event.
Default Value:
: - null
this.onwheel = (event) => {
//some function here that happens on wheel
}
The display object container that contains this display object.
Default Value:
: - undefined
parentRenderLayerIRenderLayerreadonlyinherited
The RenderLayer this container belongs to, if any. If it belongs to a RenderLayer, it will be rendered from the RenderLayer's position in the scene.
The center of rotation, scaling, and skewing for this display object in its local space. The position
is the projection of pivot
in the parent's local space.
By default, the pivot is the origin (0, 0).
Since:
: - 4.0.0
positionObservablePointinherited
The coordinate of the object relative to the local coordinates of the parent.
Since:
: - 4.0.0
The relative group transform is a transform relative to the render group it belongs too. It will include all parent transforms and up to the render group (think of it as kind of like a stage - but the stage can be nested). If this container is is self a render group matrix will be relative to its parent render group
renderableinherited
Can this object be rendered, if false the object will not be drawn but the transform will still be updated.
rotationnumberinherited
The rotation of the object in radians. 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
The scale factors of this object along the local coordinate axes.
The default scale is (1, 1).
Since:
: - 4.0.0
The skew factor for the object in radians.
Since:
: - 4.0.0
sortableChildrenbooleaninherited
If set to true, the container will sort its children by zIndex
value when the next render is called, or manually if sortChildren()
is called.
This actually changes the order of elements in the array, so should be treated as a basic solution that is not performant compared to other solutions, such as PixiJS Layers
Also be aware of that this may not work nicely with the addChildAt()
function, as the zIndex
sorting may cause the child to automatically sorted to another position.
Default Value:
: - false
sortDirtybooleaninherited
Should children be sorted by zIndex at the next render call.
Will get automatically set to true if a new child is added, or if a child's zIndex changes.
Default Value:
: - false
tabIndexnumberinherited
Default Value:
: - 0
TODO
: - Needs docs.
tintnumberinherited
The tint applied to the sprite. This is a hex value.
A value of 0xFFFFFF will remove any tint effect.
Default Value:
: - 0xFFFFFF
uidnumberreadonlyinherited
unique id for this container
updateCacheTexture() => voidinherited
Updates the cached texture of this container. This will flag the container's cached texture to be redrawn on the next render.
visibleinherited
The visibility of the object. If false the object will not be drawn, and the transform will not be updated.
widthnumberinherited
The width of the Container, setting this will actually modify the scale to achieve the value set.
worldTransformreadonlyinherited
Current transform of the object based on world (parent) factors.
xnumberinherited
The position of the container on the x axis relative to the local coordinates of the parent. An alias to position.x
ynumberinherited
The position of the container on the y axis relative to the local coordinates of the parent. An alias to position.y
From class Graphics
arc (...x, y, radius, startAngle, endAngle, counterclockwise) thisinherited
See scene_graphics_shared_Graphics.ts.html:258
Adds an arc to the current path, which is centered at (x, y) with the specified radius, starting and ending angles, and direction.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["arc"]> | The x-coordinate of the arc's center. |
y | The y-coordinate of the arc's center. | |
radius | The arc's radius. | |
startAngle | The starting angle, in radians. | |
endAngle | The ending angle, in radians. | |
counterclockwise | (Optional) Specifies whether the arc is drawn counterclockwise (true) or clockwise (false). Defaults to false. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcTo (...x1, y1, x2, y2, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:275
Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line if necessary.
Name | Type | Description |
---|---|---|
x1 | Parameters<GraphicsContext["arcTo"]> | The x-coordinate of the first control point. |
y1 | The y-coordinate of the first control point. | |
x2 | The x-coordinate of the second control point. | |
y2 | The y-coordinate of the second control point. | |
radius | The arc's radius. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcToSvg (...rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:290
Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
Name | Type | Description |
---|---|---|
rx | Parameters<GraphicsContext["arcToSvg"]> | The x-radius of the ellipse. |
ry | The y-radius of the ellipse. | |
xAxisRotation | The rotation of the ellipse's x-axis relative to the x-axis of the coordinate system, in degrees. | |
largeArcFlag | Determines if the arc should be greater than or less than 180 degrees. | |
sweepFlag | Determines if the arc should be swept in a positive angle direction. | |
x | The x-coordinate of the arc's end point. | |
y | The y-coordinate of the arc's end point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
beginFill (color, alpha)Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:744
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
beginPath () thisinherited
See scene_graphics_shared_Graphics.ts.html:240
Resets the current path. Any previous path and its commands are discarded and a new path is started. This is typically called before beginning a new shape or series of drawing commands.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
bezierCurveTo (...cp1x, cp1y, cp2x, cp2y, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:309
Adds a cubic Bezier curve to the path. It requires three points: the first two are control points and the third one is the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cp1x | Parameters<GraphicsContext["bezierCurveTo"]> | The x-coordinate of the first control point. |
cp1y | The y-coordinate of the first control point. | |
cp2x | The x-coordinate of the second control point. | |
cp2y | The y-coordinate of the second control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
chamferRect (...x, y, width, height, chamfer, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:517
Draw Rectangle with chamfer corners. These are angled corners.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["chamferRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
chamfer | non-zero real number, size of corner cutout | |
transform |
Type | Description |
---|---|
this |
circle (...x, y, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:352
Draws a circle shape. This method adds a new circle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["circle"]> | The x-coordinate of the center of the circle. |
y | The y-coordinate of the center of the circle. | |
radius | The radius of the circle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
clear () thisinherited
See scene_graphics_shared_Graphics.ts.html:663
Clears all drawing commands from the graphics context, effectively resetting it. This includes clearing the path, and optionally resetting transformations to the identity matrix.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
See scene_graphics_shared_Graphics.ts.html:697
Creates a new Graphics object. Note that only the context of the object is cloned, not its transform (position,scale,etc)
Name | Type | Default | Description |
---|---|---|---|
deep | boolean | false | Whether to create a deep clone of the graphics object. If false, the context will be shared between the two objects (default false). If true, the context will be cloned (recommended if you need to modify the context in any way). |
Type | Description |
---|---|
Graphics |
|
closePath () thisinherited
See scene_graphics_shared_Graphics.ts.html:329
Closes the current path by drawing a straight line back to the start. If the shape is already closed or there are no points in the path, this method does nothing.
Type | Description |
---|---|
this | The instance of the current object for chaining. |
containsPoint (point)inherited
See scene_graphics_shared_Graphics.ts.html:120
Checks if the object contains the given point.
Name | Type | Description |
---|---|---|
point | PointData | The point to check |
cut () thisinherited
See scene_graphics_shared_Graphics.ts.html:249
Applies a cutout to the last drawn shape. This is used to create holes or complex shapes by subtracting a path from the previously drawn path. If a hole is not completely in a shape, it will fail to cut correctly!
Type | Description |
---|---|
this |
destroy (options) voidinherited
See scene_graphics_shared_Graphics.ts.html:129
Destroys this graphics renderable and optionally its context.
If the context was created by this graphics and destroy(false)
or destroy()
is called then the context will still be destroyed.
If you want to explicitly not destroy this context that this graphics created, then you should pass destroy({ context: false })
If the context was passed in as an argument to the constructor then it will not be destroyed
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
options | DestroyOptions | <optional> | Options parameter. A boolean will act as if all options | |
options.texture | boolean | <optional> | false | Should destroy the texture of the graphics context |
options.textureSource | boolean | <optional> | false | Should destroy the texture source of the graphics context |
options.context | boolean | <optional> | false | Should destroy the context |
drawCircle (...args) thisDeprecated`` : since 8.0.0 Use Graphics#circle insteadinherited
See scene_graphics_shared_Graphics.ts.html:790
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawEllipse (...args) thisDeprecated`` : since 8.0.0 Use Graphics#ellipse insteadinherited
See scene_graphics_shared_Graphics.ts.html:803
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawPolygon (...args) thisDeprecated`` : since 8.0.0 Use Graphics#poly insteadinherited
See scene_graphics_shared_Graphics.ts.html:816
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#rect insteadinherited
See scene_graphics_shared_Graphics.ts.html:829
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRoundedRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#roundRect insteadinherited
See scene_graphics_shared_Graphics.ts.html:842
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawStar (...args) thisDeprecated`` : since 8.0.0 Use Graphics#star insteadinherited
See scene_graphics_shared_Graphics.ts.html:855
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
ellipse (...x, y, radiusX, radiusY) thisinherited
See scene_graphics_shared_Graphics.ts.html:338
Draws an ellipse at the specified location and with the given x and y radii. An optional transformation can be applied, allowing for rotation, scaling, and translation.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["ellipse"]> | The x-coordinate of the center of the ellipse. |
y | The y-coordinate of the center of the ellipse. | |
radiusX | The horizontal radius of the ellipse. | |
radiusY | The vertical radius of the ellipse. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
endFill ()Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:767
fill (...style) thisinherited
See scene_graphics_shared_Graphics.ts.html:193
Fills the current or given path with the current fill style. This method can optionally take a color and alpha for a simple fill, or a more complex FillStyle object for advanced fills.
Name | Type | Description |
---|---|---|
style | FillInput | (Optional) The style to fill the path with. Can be a color, gradient, pattern, or a complex style object. If omitted, uses the current fill style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
fill (color, alpha) thisDeprecated`` : 8.0.0inherited
See scene_graphics_shared_Graphics.ts.html:201
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
Type | Description |
---|---|
this |
filletRect (...x, y, width, height, fillet) thisinherited
See scene_graphics_shared_Graphics.ts.html:503
Draw Rectangle with fillet corners. This is much like rounded rectangle however it support negative numbers as well for the corner radius.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["filletRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
fillet | accept negative or positive values |
Type | Description |
---|---|
this |
See scene_graphics_shared_Graphics.ts.html:576
Returns the current transformation matrix of the graphics context.
Type | Description |
---|---|
Matrix | The current transformation matrix. |
lineStyle (width, color, alpha) thisDeprecated`` : since 8.0.0 Use Graphics#setStrokeStyle insteadinherited
See scene_graphics_shared_Graphics.ts.html:720
Name | Type | Attributes | Description |
---|---|---|---|
width | number | <optional> | |
color | ColorSource | <optional> | |
alpha | number | <optional> |
Type | Description |
---|---|
this |
lineTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:374
Connects the current point to a new point with a straight line. This method updates the current path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["lineTo"]> | The x-coordinate of the new point to connect to. |
y | The y-coordinate of the new point to connect to. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
moveTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:385
Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["moveTo"]> | The x-coordinate for the starting point. |
y | The y-coordinate for the starting point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
path (...path) thisinherited
See scene_graphics_shared_Graphics.ts.html:364
Adds another GraphicsPath
to this path, optionally applying a transformation.
Name | Type | Description |
---|---|---|
path | Parameters<GraphicsContext["path"]> | The GraphicsPath to add. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
poly (...points, close) thisinherited
See scene_graphics_shared_Graphics.ts.html:440
Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons, which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled, rotated, or translated as needed.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["poly"]> | An array of numbers, or an array of PointData objects eg [{x,y}, {x,y}, {x,y}] representing the x and y coordinates, of the polygon's vertices, in sequence. |
close | A boolean indicating whether to close the polygon path. True by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
quadraticCurveTo (...cpx, cpy, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:396
Adds a quadratic curve to the path. It requires two points: the control point and the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cpx | Parameters<GraphicsContext["quadraticCurveTo"]> | The x-coordinate of the control point. |
cpy | The y-coordinate of the control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
rect (...x, y, w, h) thisinherited
See scene_graphics_shared_Graphics.ts.html:411
Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["rect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
regularPoly (...x, y, radius, sides, rotation, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:454
Draws a regular polygon with a specified number of sides. All sides and angles are equal.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["regularPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. | |
transform | An optional Matrix object to apply a transformation to the polygon. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
resetTransform () thisinherited
See scene_graphics_shared_Graphics.ts.html:584
Resets the current transformation matrix to the identity matrix, effectively removing any transformations (rotation, scaling, translation) previously applied.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
restore (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:562
Restores the most recently saved graphics state by popping the top of the graphics state stack. This includes transformations, fill styles, and stroke styles.
Name | Type | Description |
---|---|---|
args | Parameters<GraphicsContext["restore"]> |
Type | Description |
---|---|
this |
rotateTransform (...angle) thisinherited
See scene_graphics_shared_Graphics.ts.html:593
Applies a rotation transformation to the graphics context around the current origin.
Name | Type | Description |
---|---|---|
angle | Parameters<GraphicsContext["rotate"]> | The angle of rotation in radians. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
roundPoly (...x, y, radius, sides, corner, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:469
Draws a polygon with rounded corners. Similar to regularPoly
but with the ability to round the corners of the polygon.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
corner | The radius of the rounding of the corners. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundRect (...x, y, w, h, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:424
Draws a rectangle with rounded corners. The corner radius can be specified to determine how rounded the corners should be. An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundRect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. | |
radius | The radius of the rectangle's corners. If not specified, corners will be sharp. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundShape (...points, radius, useQuadratic, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:485
Draws a shape with rounded corners. This function supports custom radius for each corner of the shape. Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["roundShape"]> | An array of RoundedPoint representing the corners of the shape to draw. A minimum of 3 points is required. |
radius | The default radius for the corners. This radius is applied to all corners unless overridden in points . |
|
useQuadratic | If set to true, rounded corners are drawn using a quadraticCurve method instead of an arc method. Defaults to false. | |
smoothness | Specifies the smoothness of the curve when useQuadratic is true. Higher values make the curve smoother. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
save () thisinherited
See scene_graphics_shared_Graphics.ts.html:571
Saves the current graphics state, including transformations, fill styles, and stroke styles, onto a stack.
Type | Description |
---|---|
this |
scaleTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:603
Applies a scaling transformation to the graphics context, scaling drawings by x horizontally and by y vertically.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["scale"]> | The scale factor in the horizontal direction. |
y | (Optional) The scale factor in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setFillStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:169
Sets the current fill style of the graphics context. The fill style can be a color, gradient, pattern, or a more complex style defined by a FillStyle object.
Name | Type | Description |
---|---|---|
args | FillInput | The fill style to apply. This can be a simple color, a gradient or pattern object, or a FillStyle or ConvertedFillStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setStrokeStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:181
Sets the current stroke style of the graphics context. Similar to fill styles, stroke styles can encompass colors, gradients, patterns, or more detailed configurations via a StrokeStyle object.
Name | Type | Description |
---|---|---|
args | StrokeInput | The stroke style to apply. Can be defined as a color, a gradient or pattern, or a StrokeStyle or ConvertedStrokeStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setTransform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:615
Sets the current transformation matrix of the graphics context to the specified matrix or values. This replaces the current transformation matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
star (...x, y, points, radius, innerRadius, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:531
Draws a star shape centered at a specified location. This method allows for the creation of stars with a variable number of points, outer radius, optional inner radius, and rotation. The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points. An optional transformation can be applied to scale, rotate, or translate the star as needed.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["star"]> | The x-coordinate of the center of the star. |
y | The y-coordinate of the center of the star. | |
points | The number of points of the star. | |
radius | The outer radius of the star (distance from the center to the outer points). | |
innerRadius | Optional. The inner radius of the star (distance from the center to the inner points between the outer points). If not provided, defaults to half of the radius . |
|
rotation | Optional. The rotation of the star in radians, where 0 is aligned with the y-axis. Defaults to 0, meaning one point is directly upward. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
stroke (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:207
Strokes the current path with the current stroke style. This method can take an optional FillStyle parameter to define the stroke's appearance, including its color, width, and other properties.
Name | Type | Description |
---|---|---|
args | FillStyle | (Optional) The stroke style to apply. Can be defined as a simple color or a more complex style object. If omitted, uses the current stroke style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
svg (...svg) thisinherited
See scene_graphics_shared_Graphics.ts.html:552
Parses and renders an SVG string into the graphics context. This allows for complex shapes and paths defined in SVG format to be drawn within the graphics context.
Name | Type | Description |
---|---|---|
svg | Parameters<GraphicsContext["svg"]> | The SVG string to be parsed and rendered. |
Type | Description |
---|---|
this |
texture (...texture, tint, dx, dy, dw, dh) thisinherited
See scene_graphics_shared_Graphics.ts.html:218
Adds a texture to the graphics context. This method supports multiple overloads for specifying the texture, tint, and dimensions. If only a texture is provided, it uses the texture's width and height for drawing. Additional parameters allow for specifying a tint color, and custom dimensions for the texture drawing area.
Name | Type | Description |
---|---|---|
texture | [Texture, unknown, unknown, unknown, unknown, unknown] | The Texture object to use. |
tint | (Optional) A ColorSource to tint the texture. If not provided, defaults to white (0xFFFFFF). | |
dx | (Optional) The x-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dy | (Optional) The y-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dw | (Optional) The width of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame width. | |
dh | (Optional) The height of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame height. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
transform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:633
Applies the specified transformation matrix to the current graphics context by multiplying the current matrix with the specified matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
translateTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:651
Applies a translation transformation to the graphics context, moving the origin by the specified amounts.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["translate"]> | The amount to translate in the horizontal direction. |
y | (Optional) The amount to translate in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arc (...x, y, radius, startAngle, endAngle, counterclockwise) thisinherited
See scene_graphics_shared_Graphics.ts.html:258
Adds an arc to the current path, which is centered at (x, y) with the specified radius, starting and ending angles, and direction.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["arc"]> | The x-coordinate of the arc's center. |
y | The y-coordinate of the arc's center. | |
radius | The arc's radius. | |
startAngle | The starting angle, in radians. | |
endAngle | The ending angle, in radians. | |
counterclockwise | (Optional) Specifies whether the arc is drawn counterclockwise (true) or clockwise (false). Defaults to false. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcTo (...x1, y1, x2, y2, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:275
Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line if necessary.
Name | Type | Description |
---|---|---|
x1 | Parameters<GraphicsContext["arcTo"]> | The x-coordinate of the first control point. |
y1 | The y-coordinate of the first control point. | |
x2 | The x-coordinate of the second control point. | |
y2 | The y-coordinate of the second control point. | |
radius | The arc's radius. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
arcToSvg (...rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:290
Adds an SVG-style arc to the path, allowing for elliptical arcs based on the SVG spec.
Name | Type | Description |
---|---|---|
rx | Parameters<GraphicsContext["arcToSvg"]> | The x-radius of the ellipse. |
ry | The y-radius of the ellipse. | |
xAxisRotation | The rotation of the ellipse's x-axis relative to the x-axis of the coordinate system, in degrees. | |
largeArcFlag | Determines if the arc should be greater than or less than 180 degrees. | |
sweepFlag | Determines if the arc should be swept in a positive angle direction. | |
x | The x-coordinate of the arc's end point. | |
y | The y-coordinate of the arc's end point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
beginFill (color, alpha)Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:744
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
beginPath () thisinherited
See scene_graphics_shared_Graphics.ts.html:240
Resets the current path. Any previous path and its commands are discarded and a new path is started. This is typically called before beginning a new shape or series of drawing commands.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
bezierCurveTo (...cp1x, cp1y, cp2x, cp2y, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:309
Adds a cubic Bezier curve to the path. It requires three points: the first two are control points and the third one is the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cp1x | Parameters<GraphicsContext["bezierCurveTo"]> | The x-coordinate of the first control point. |
cp1y | The y-coordinate of the first control point. | |
cp2x | The x-coordinate of the second control point. | |
cp2y | The y-coordinate of the second control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
chamferRect (...x, y, width, height, chamfer, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:517
Draw Rectangle with chamfer corners. These are angled corners.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["chamferRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
chamfer | non-zero real number, size of corner cutout | |
transform |
Type | Description |
---|---|
this |
circle (...x, y, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:352
Draws a circle shape. This method adds a new circle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["circle"]> | The x-coordinate of the center of the circle. |
y | The y-coordinate of the center of the circle. | |
radius | The radius of the circle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
clear () thisinherited
See scene_graphics_shared_Graphics.ts.html:663
Clears all drawing commands from the graphics context, effectively resetting it. This includes clearing the path, and optionally resetting transformations to the identity matrix.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
See scene_graphics_shared_Graphics.ts.html:697
Creates a new Graphics object. Note that only the context of the object is cloned, not its transform (position,scale,etc)
Name | Type | Default | Description |
---|---|---|---|
deep | boolean | false | Whether to create a deep clone of the graphics object. If false, the context will be shared between the two objects (default false). If true, the context will be cloned (recommended if you need to modify the context in any way). |
Type | Description |
---|---|
Graphics |
|
closePath () thisinherited
See scene_graphics_shared_Graphics.ts.html:329
Closes the current path by drawing a straight line back to the start. If the shape is already closed or there are no points in the path, this method does nothing.
Type | Description |
---|---|
this | The instance of the current object for chaining. |
containsPoint (point)inherited
See scene_graphics_shared_Graphics.ts.html:120
Checks if the object contains the given point.
Name | Type | Description |
---|---|---|
point | PointData | The point to check |
cut () thisinherited
See scene_graphics_shared_Graphics.ts.html:249
Applies a cutout to the last drawn shape. This is used to create holes or complex shapes by subtracting a path from the previously drawn path. If a hole is not completely in a shape, it will fail to cut correctly!
Type | Description |
---|---|
this |
destroy (options) voidinherited
See scene_graphics_shared_Graphics.ts.html:129
Destroys this graphics renderable and optionally its context.
If the context was created by this graphics and destroy(false)
or destroy()
is called then the context will still be destroyed.
If you want to explicitly not destroy this context that this graphics created, then you should pass destroy({ context: false })
If the context was passed in as an argument to the constructor then it will not be destroyed
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
options | DestroyOptions | <optional> | Options parameter. A boolean will act as if all options | |
options.texture | boolean | <optional> | false | Should destroy the texture of the graphics context |
options.textureSource | boolean | <optional> | false | Should destroy the texture source of the graphics context |
options.context | boolean | <optional> | false | Should destroy the context |
drawCircle (...args) thisDeprecated`` : since 8.0.0 Use Graphics#circle insteadinherited
See scene_graphics_shared_Graphics.ts.html:790
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawEllipse (...args) thisDeprecated`` : since 8.0.0 Use Graphics#ellipse insteadinherited
See scene_graphics_shared_Graphics.ts.html:803
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawPolygon (...args) thisDeprecated`` : since 8.0.0 Use Graphics#poly insteadinherited
See scene_graphics_shared_Graphics.ts.html:816
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#rect insteadinherited
See scene_graphics_shared_Graphics.ts.html:829
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawRoundedRect (...args) thisDeprecated`` : since 8.0.0 Use Graphics#roundRect insteadinherited
See scene_graphics_shared_Graphics.ts.html:842
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
drawStar (...args) thisDeprecated`` : since 8.0.0 Use Graphics#star insteadinherited
See scene_graphics_shared_Graphics.ts.html:855
Name | Type | Description |
---|---|---|
args | any |
Type | Description |
---|---|
this |
ellipse (...x, y, radiusX, radiusY) thisinherited
See scene_graphics_shared_Graphics.ts.html:338
Draws an ellipse at the specified location and with the given x and y radii. An optional transformation can be applied, allowing for rotation, scaling, and translation.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["ellipse"]> | The x-coordinate of the center of the ellipse. |
y | The y-coordinate of the center of the ellipse. | |
radiusX | The horizontal radius of the ellipse. | |
radiusY | The vertical radius of the ellipse. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
endFill ()Deprecated`` : since 8.0.0 Use Graphics#fill insteadinherited
See scene_graphics_shared_Graphics.ts.html:767
fill (...style) thisinherited
See scene_graphics_shared_Graphics.ts.html:193
Fills the current or given path with the current fill style. This method can optionally take a color and alpha for a simple fill, or a more complex FillStyle object for advanced fills.
Name | Type | Description |
---|---|---|
style | FillInput | (Optional) The style to fill the path with. Can be a color, gradient, pattern, or a complex style object. If omitted, uses the current fill style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
fill (color, alpha) thisDeprecated`` : 8.0.0inherited
See scene_graphics_shared_Graphics.ts.html:201
Name | Type | Attributes | Description |
---|---|---|---|
color | ColorSource | ||
alpha | number | <optional> |
Type | Description |
---|---|
this |
filletRect (...x, y, width, height, fillet) thisinherited
See scene_graphics_shared_Graphics.ts.html:503
Draw Rectangle with fillet corners. This is much like rounded rectangle however it support negative numbers as well for the corner radius.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["filletRect"]> | Upper left corner of rect |
y | Upper right corner of rect | |
width | Width of rect | |
height | Height of rect | |
fillet | accept negative or positive values |
Type | Description |
---|---|
this |
See scene_graphics_shared_Graphics.ts.html:576
Returns the current transformation matrix of the graphics context.
Type | Description |
---|---|
Matrix | The current transformation matrix. |
lineStyle (width, color, alpha) thisDeprecated`` : since 8.0.0 Use Graphics#setStrokeStyle insteadinherited
See scene_graphics_shared_Graphics.ts.html:720
Name | Type | Attributes | Description |
---|---|---|---|
width | number | <optional> | |
color | ColorSource | <optional> | |
alpha | number | <optional> |
Type | Description |
---|---|
this |
lineTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:374
Connects the current point to a new point with a straight line. This method updates the current path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["lineTo"]> | The x-coordinate of the new point to connect to. |
y | The y-coordinate of the new point to connect to. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
moveTo (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:385
Sets the starting point for a new sub-path. Any subsequent drawing commands are considered part of this path.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["moveTo"]> | The x-coordinate for the starting point. |
y | The y-coordinate for the starting point. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
path (...path) thisinherited
See scene_graphics_shared_Graphics.ts.html:364
Adds another GraphicsPath
to this path, optionally applying a transformation.
Name | Type | Description |
---|---|---|
path | Parameters<GraphicsContext["path"]> | The GraphicsPath to add. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
poly (...points, close) thisinherited
See scene_graphics_shared_Graphics.ts.html:440
Draws a polygon shape by specifying a sequence of points. This method allows for the creation of complex polygons, which can be both open and closed. An optional transformation can be applied, enabling the polygon to be scaled, rotated, or translated as needed.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["poly"]> | An array of numbers, or an array of PointData objects eg [{x,y}, {x,y}, {x,y}] representing the x and y coordinates, of the polygon's vertices, in sequence. |
close | A boolean indicating whether to close the polygon path. True by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
quadraticCurveTo (...cpx, cpy, x, y, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:396
Adds a quadratic curve to the path. It requires two points: the control point and the end point. The starting point is the last point in the current path.
Name | Type | Description |
---|---|---|
cpx | Parameters<GraphicsContext["quadraticCurveTo"]> | The x-coordinate of the control point. |
cpy | The y-coordinate of the control point. | |
x | The x-coordinate of the end point. | |
y | The y-coordinate of the end point. | |
smoothness | Optional parameter to adjust the smoothness of the curve. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
rect (...x, y, w, h) thisinherited
See scene_graphics_shared_Graphics.ts.html:411
Draws a rectangle shape. This method adds a new rectangle path to the current drawing.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["rect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
regularPoly (...x, y, radius, sides, rotation, transform) thisinherited
See scene_graphics_shared_Graphics.ts.html:454
Draws a regular polygon with a specified number of sides. All sides and angles are equal.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["regularPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. | |
transform | An optional Matrix object to apply a transformation to the polygon. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
resetTransform () thisinherited
See scene_graphics_shared_Graphics.ts.html:584
Resets the current transformation matrix to the identity matrix, effectively removing any transformations (rotation, scaling, translation) previously applied.
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
restore (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:562
Restores the most recently saved graphics state by popping the top of the graphics state stack. This includes transformations, fill styles, and stroke styles.
Name | Type | Description |
---|---|---|
args | Parameters<GraphicsContext["restore"]> |
Type | Description |
---|---|
this |
rotateTransform (...angle) thisinherited
See scene_graphics_shared_Graphics.ts.html:593
Applies a rotation transformation to the graphics context around the current origin.
Name | Type | Description |
---|---|---|
angle | Parameters<GraphicsContext["rotate"]> | The angle of rotation in radians. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
roundPoly (...x, y, radius, sides, corner, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:469
Draws a polygon with rounded corners. Similar to regularPoly
but with the ability to round the corners of the polygon.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundPoly"]> | The x-coordinate of the center of the polygon. |
y | The y-coordinate of the center of the polygon. | |
radius | The radius of the circumscribed circle of the polygon. | |
sides | The number of sides of the polygon. Must be 3 or more. | |
corner | The radius of the rounding of the corners. | |
rotation | The rotation angle of the polygon, in radians. Zero by default. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundRect (...x, y, w, h, radius) thisinherited
See scene_graphics_shared_Graphics.ts.html:424
Draws a rectangle with rounded corners. The corner radius can be specified to determine how rounded the corners should be. An optional transformation can be applied, which allows for rotation, scaling, and translation of the rectangle.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["roundRect"]> | The x-coordinate of the top-left corner of the rectangle. |
y | The y-coordinate of the top-left corner of the rectangle. | |
w | The width of the rectangle. | |
h | The height of the rectangle. | |
radius | The radius of the rectangle's corners. If not specified, corners will be sharp. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
roundShape (...points, radius, useQuadratic, smoothness) thisinherited
See scene_graphics_shared_Graphics.ts.html:485
Draws a shape with rounded corners. This function supports custom radius for each corner of the shape. Optionally, corners can be rounded using a quadratic curve instead of an arc, providing a different aesthetic.
Name | Type | Description |
---|---|---|
points | Parameters<GraphicsContext["roundShape"]> | An array of RoundedPoint representing the corners of the shape to draw. A minimum of 3 points is required. |
radius | The default radius for the corners. This radius is applied to all corners unless overridden in points . |
|
useQuadratic | If set to true, rounded corners are drawn using a quadraticCurve method instead of an arc method. Defaults to false. | |
smoothness | Specifies the smoothness of the curve when useQuadratic is true. Higher values make the curve smoother. |
Type | Description |
---|---|
this | The instance of the current object for chaining. |
save () thisinherited
See scene_graphics_shared_Graphics.ts.html:571
Saves the current graphics state, including transformations, fill styles, and stroke styles, onto a stack.
Type | Description |
---|---|
this |
scaleTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:603
Applies a scaling transformation to the graphics context, scaling drawings by x horizontally and by y vertically.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["scale"]> | The scale factor in the horizontal direction. |
y | (Optional) The scale factor in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setFillStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:169
Sets the current fill style of the graphics context. The fill style can be a color, gradient, pattern, or a more complex style defined by a FillStyle object.
Name | Type | Description |
---|---|---|
args | FillInput | The fill style to apply. This can be a simple color, a gradient or pattern object, or a FillStyle or ConvertedFillStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setStrokeStyle (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:181
Sets the current stroke style of the graphics context. Similar to fill styles, stroke styles can encompass colors, gradients, patterns, or more detailed configurations via a StrokeStyle object.
Name | Type | Description |
---|---|---|
args | StrokeInput | The stroke style to apply. Can be defined as a color, a gradient or pattern, or a StrokeStyle or ConvertedStrokeStyle object. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
setTransform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:615
Sets the current transformation matrix of the graphics context to the specified matrix or values. This replaces the current transformation matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
star (...x, y, points, radius, innerRadius, rotation) thisinherited
See scene_graphics_shared_Graphics.ts.html:531
Draws a star shape centered at a specified location. This method allows for the creation of stars with a variable number of points, outer radius, optional inner radius, and rotation. The star is drawn as a closed polygon with alternating outer and inner vertices to create the star's points. An optional transformation can be applied to scale, rotate, or translate the star as needed.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["star"]> | The x-coordinate of the center of the star. |
y | The y-coordinate of the center of the star. | |
points | The number of points of the star. | |
radius | The outer radius of the star (distance from the center to the outer points). | |
innerRadius | Optional. The inner radius of the star (distance from the center to the inner points between the outer points). If not provided, defaults to half of the radius . |
|
rotation | Optional. The rotation of the star in radians, where 0 is aligned with the y-axis. Defaults to 0, meaning one point is directly upward. |
Type | Description |
---|---|
this | The instance of the current object for chaining further drawing commands. |
stroke (...args) thisinherited
See scene_graphics_shared_Graphics.ts.html:207
Strokes the current path with the current stroke style. This method can take an optional FillStyle parameter to define the stroke's appearance, including its color, width, and other properties.
Name | Type | Description |
---|---|---|
args | FillStyle | (Optional) The stroke style to apply. Can be defined as a simple color or a more complex style object. If omitted, uses the current stroke style. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
svg (...svg) thisinherited
See scene_graphics_shared_Graphics.ts.html:552
Parses and renders an SVG string into the graphics context. This allows for complex shapes and paths defined in SVG format to be drawn within the graphics context.
Name | Type | Description |
---|---|---|
svg | Parameters<GraphicsContext["svg"]> | The SVG string to be parsed and rendered. |
Type | Description |
---|---|
this |
texture (...texture, tint, dx, dy, dw, dh) thisinherited
See scene_graphics_shared_Graphics.ts.html:218
Adds a texture to the graphics context. This method supports multiple overloads for specifying the texture, tint, and dimensions. If only a texture is provided, it uses the texture's width and height for drawing. Additional parameters allow for specifying a tint color, and custom dimensions for the texture drawing area.
Name | Type | Description |
---|---|---|
texture | [Texture, unknown, unknown, unknown, unknown, unknown] | The Texture object to use. |
tint | (Optional) A ColorSource to tint the texture. If not provided, defaults to white (0xFFFFFF). | |
dx | (Optional) The x-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dy | (Optional) The y-coordinate in the destination canvas at which to place the top-left corner of the source image. | |
dw | (Optional) The width of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame width. | |
dh | (Optional) The height of the rectangle within the source image to draw onto the destination canvas. If not provided, uses the texture's frame height. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
transform (...a, b, c, d, dx, dy) thisinherited
See scene_graphics_shared_Graphics.ts.html:633
Applies the specified transformation matrix to the current graphics context by multiplying the current matrix with the specified matrix.
Name | Type | Description |
---|---|---|
a | [Matrix] | [number, number, number, number, number, number] | The value for the a property of the matrix, or a Matrix object to use directly. |
b | The value for the b property of the matrix. | |
c | The value for the c property of the matrix. | |
d | The value for the d property of the matrix. | |
dx | The value for the tx (translate x) property of the matrix. | |
dy | The value for the ty (translate y) property of the matrix. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
translateTransform (...x, y) thisinherited
See scene_graphics_shared_Graphics.ts.html:651
Applies a translation transformation to the graphics context, moving the origin by the specified amounts.
Name | Type | Description |
---|---|---|
x | Parameters<GraphicsContext["translate"]> | The amount to translate in the horizontal direction. |
y | (Optional) The amount to translate in the vertical direction. If not specified, the x value is used for both directions. |
Type | Description |
---|---|
this | The instance of the current GraphicsContext for method chaining. |
From class Container
_getGlobalBoundsRecursive (factorRenderLayers, bounds, currentLayer) voidinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:31
Recursively calculates the global bounds for the container and its children. This method is used internally by getFastGlobalBounds to traverse the scene graph.
Name | Type | Description |
---|---|---|
factorRenderLayers | boolean | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | The bounds object to update with the calculated values. |
currentLayer | IRenderLayer | The current render layer being processed. |
addChild (...children) Containerinherited
See scene_container_Container.ts.html:630
Adds one or more children to the container.
Multiple items can be added like so: myContainer.addChild(thingOne, thingTwo, thingThree)
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to add to the container |
Type | Description |
---|---|
Container |
|
addChildAt (child, index) Containerinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:151
Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown. If the child is already in this container, it will be moved to the specified index.
Name | Type | Description |
---|---|---|
child | Container | The child to add. |
index | number | The absolute index where the child will be positioned at the end of the operation. |
Type | Description |
---|---|
Container | The child that was added. |
addEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:681
Unlike on
or addListener
which are methods from EventEmitter, addEventListener
seeks to be compatible with the DOM's addEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event to listen to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | AddListenerOptions | <optional> | Listener options, used for capture phase. |
// Tell the user whether they did a single, double, triple, or nth click.
button.addEventListener('click', {
handleEvent(e): {
let prefix;
switch (e.detail) {
case 1: prefix = 'single'; break;
case 2: prefix = 'double'; break;
case 3: prefix = 'triple'; break;
default: prefix = e.detail + 'th'; break;
}
console.log('That was a ' + prefix + 'click');
}
});
// But skip the first click!
button.parent.addEventListener('click', function blockClickOnce(e) {
e.stopImmediatePropagation();
button.parent.removeEventListener('click', blockClickOnce, true);
}, {
capture: true,
});
cacheAsTexture (val) voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:13
Caches this container as a texture. This allows the container to be rendered as a single texture, which can improve performance for complex static containers.
Name | Type | Description |
---|---|---|
val | boolean | CacheAsTextureOptions | If true, enables caching with default options. If false, disables caching. Can also pass options object to configure caching behavior. |
collectRenderables (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:15
Collects all renderables from the container and its children, adding them to the instruction set. This method decides whether to use a simple or advanced collection method based on the container's properties.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesSimple (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:25
Collects renderables using a simple method, suitable for containers marked as simple. This method iterates over the container's children and adds their renderables to the instruction set.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesWithEffects (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:35
Collects renderables using an advanced method, suitable for containers with complex processing needs. This method handles additional effects and transformations that may be applied to the renderables.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
disableRenderGroup () voidinherited
See scene_container_Container.ts.html:831
This will disable the render group for this container.
dispatchEvent (e) booleaninherited
See events_FederatedEventTarget.ts.html:772
Dispatch the event on this Container using the event's EventBoundary.
The target of the event is set to this
and the defaultPrevented
flag is cleared before dispatch.
Name | Type | Description |
---|---|---|
e | Event | The event to dispatch. |
Type | Description |
---|---|
boolean | Whether the preventDefault() method was not invoked. |
// Reuse a click event!
button.dispatchEvent(clickEvent);
enableRenderGroup () voidinherited
See scene_container_Container.ts.html:807
Calling this enables a render group for this container. This means it will be rendered as a separate set of instructions. The transform of the container will also be handled on the GPU rather than the CPU.
eventMode (value)inherited
See events_FederatedEventTarget.ts.html:601
Enable interaction events for the Container. Touch, pointer and mouse. There are 5 types of interaction settings:
'none'
: Ignores all interaction events, even on its children.'passive'
: (default) Does not emit events and ignores all hit testing on itself and non-interactive children. Interactive children will still emit events.'auto'
: Does not emit events but is hit tested if parent is interactive. Same asinteractive = false
in v7'static'
: Emit events and is hit tested. Same asinteraction = true
in v7'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
Name | Type | Description |
---|---|---|
value |
Since:
: - 7.2.0
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.on('tap', (event) => {
// Handle event
});
See scene_container_container-mixins_effectsMixin.ts.html:238
The area the filter is applied to. This is used as more of an optimization rather than figuring out the dimensions of the displayObject each frame you can set this rectangle.
Also works as an interaction mask.
Type | Description |
---|---|
Rectangle |
filters () readonlyinherited
See scene_container_container-mixins_effectsMixin.ts.html:191
Sets the filters for the displayObject. IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. To remove filters simply set this property to 'null'
.
Type | Description |
---|---|
readonly |
See scene_container_container-mixins_measureMixin.ts.html:111
Calculates and returns the (world) bounds of the display object as a Rectangle.
Name | Type | Attributes | Description |
---|---|---|---|
skipUpdate | boolean | <optional> | Setting to true will stop the transforms of the scene graph from being updated. This means the calculation returned MAY be out of date BUT will give you a nice performance boost. |
bounds | Bounds | <optional> | Optional bounds to store the result of the bounds calculation. |
Type | Description |
---|---|
Bounds |
|
getChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:100
Returns the child at the specified index
Name | Type | Description |
---|---|---|
index | number | The index to get the child at |
Type | Description |
---|---|
U |
|
getChildByLabel (label, deep) Containerinherited
See scene_container_container-mixins_findMixin.ts.html:66
Returns the first child in the container with the specified label.
Recursive searches are done in a pre-order traversal.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
Type | Description |
---|---|
Container | The child with the specified label. |
getChildByName (name, deep) ContainerDeprecated`` : since 8.0.0inherited
See scene_container_container-mixins_findMixin.ts.html:53
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
name | string | Instance name. | ||
deep | boolean | <optional> | false | Whether to search recursively |
See: getChildByLabel
Type | Description |
---|---|
Container | The child with the specified name. |
getChildIndex (child) numberinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:133
Returns the index position of a child Container instance
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The Container instance to identify |
Type | Description |
---|---|
number |
|
getChildrenByLabel (label, deep, out) Array<Container>inherited
See scene_container_container-mixins_findMixin.ts.html:103
Returns all children in the container with the specified label.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
out | Array<Container> | <optional> | [] | The array to store matching children in. |
Type | Description |
---|---|
Array<Container> | An array of children with the specified label. |
getFastGlobalBounds (factorRenderLayers, bounds) Boundsinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:17
Computes an approximate global bounding box for the container and its children. This method is optimized for speed by using axis-aligned bounding boxes (AABBs), and uses the last render results from when it updated the transforms. This function does not update them. which may result in slightly larger bounds but never smaller than the actual bounds.
for accurate (but less performant) results use container.getGlobalBounds
Name | Type | Attributes | Description |
---|---|---|---|
factorRenderLayers | boolean | <optional> | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | <optional> | The output bounds object to store the result. If not provided, a new one is created. |
Type | Description |
---|---|
Bounds | The computed bounds. |
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:15
Returns the global position of the container.
Name | Type | Default | Description |
---|---|---|---|
point | Point | The optional point to write the global value to. | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
Point |
|
See scene_container_container-mixins_measureMixin.ts.html:73
Retrieves the local bounds of the container as a Bounds object.
Type | Description |
---|---|
Bounds |
|
See scene_container_Container.ts.html:1059
Retrieves the size of the container as a Size object. This is faster than get the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
out | Size | <optional> | Optional object to store the size in. |
Type | Description |
---|---|
Size |
|
interactive (value)inherited
See events_FederatedEventTarget.ts.html:585
Enable interaction events for the Container. Touch, pointer and mouse
Name | Type | Description |
---|---|---|
value | boolean |
isCachedAsTexture () booleaninherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:46
Is this container cached as a texture?
Type | Description |
---|---|
boolean |
isInteractive () booleaninherited
See events_FederatedEventTarget.ts.html:631
Determines if the container is interactive or not
Since:
: - 7.2.0
Type | Description |
---|---|
boolean | Whether the container is interactive or not |
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.isInteractive(); // true
sprite.eventMode = 'dynamic';
sprite.isInteractive(); // true
sprite.eventMode = 'none';
sprite.isInteractive(); // false
sprite.eventMode = 'passive';
sprite.isInteractive(); // false
sprite.eventMode = 'auto';
sprite.isInteractive(); // false
mask () unknowninherited
See scene_container_container-mixins_effectsMixin.ts.html:110
Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. In PixiJS a regular mask must be a Graphics or a {@link Sprite} object. This allows for much faster masking in canvas as it utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. Otherwise, getLocalBounds
may calculate incorrect bounds, which makes the container's width and height wrong. To remove a mask, set this property to null
.
For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
Type | Description |
---|---|
unknown |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.mask = graphics;
See scene_container_container-mixins_onRenderMixin.ts.html:16
This callback is used when the container is rendered. This is where you should add your custom logic that is needed to be run every frame.
In v7 many users used updateTransform
for this, however the way v8 renders objects is different and "updateTransform" is no longer called every frame
Type | Description |
---|---|
(renderer: Renderer) => void |
const container = new Container();
container.onRender = () => {
container.rotation += 0.01;
};
removeChild (...children) Containerinherited
See scene_container_Container.ts.html:709
Removes one or more children from the container.
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to remove |
Type | Description |
---|---|
Container | The first child that was removed. |
removeChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:87
Removes a child from the specified index position.
Name | Type | Description |
---|---|---|
index | number | The index to get the child from |
Type | Description |
---|---|
U | The child that was removed. |
removeChildren (beginIndex, endIndex) ContainerChild[]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:29
Removes all children from this container that are within the begin and end indexes.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
beginIndex | number | 0 | The beginning position. | |
endIndex | number | <optional> | The ending position. Default value is size of the container. |
Type | Description |
---|---|
ContainerChild[] |
|
removeEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:748
Unlike off
or removeListener
which are methods from EventEmitter, removeEventListener
seeks to be compatible with the DOM's removeEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event the listener is bound to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | RemoveListenerOptions | <optional> | The original listener options. This is required to deregister a capture phase listener. |
removeFromParent ()inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:249
Remove the Container from its parent Container. If the Container has no parent, do nothing.
reparentChild (...child) U[0]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:258
Reparent the child to this container, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
Type | Description |
---|---|
U[0] | The first child that was reparented. |
reparentChildAt (child, index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:276
Reparent the child to this container at the specified index, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
index | number | The index to reparent the child to |
Type | Description |
---|---|
U |
setChildIndex (child, index) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:116
Changes the position of an existing child in the container
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The child Container instance for which you want to change the index number |
index | number | The resulting index number for the child container |
setFromMatrix (matrix) voidinherited
See scene_container_Container.ts.html:1154
Updates the local transform using the given matrix.
Name | Type | Description |
---|---|---|
matrix | Matrix | The matrix to use for updating the transform. |
setMask (options)inherited
See scene_container_container-mixins_effectsMixin.ts.html:132
Used to set mask and control mask options.
Name | Type | Description |
---|---|---|
options | Partial<MaskOptionsAndMask> |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.setMask({
mask: graphics,
inverse: true,
});
setSize (value, height)inherited
See scene_container_Container.ts.html:1081
Sets the size of the container to the specified width and height. This is faster than setting the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
value | number | Optional<Size, "height"> | This can be either a number or a Size object. | |
height | number | <optional> | The height to set. Defaults to the value of width if not provided. |
swapChildren (child, child2) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:221
Swaps the position of 2 Containers within this container.
Name | Type | Description |
---|---|---|
child | U | First container to swap |
child2 | U | Second container to swap |
toGlobal (position, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:37
Calculates the global position of the container.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
position | PointData | The world origin to calculate from. | ||
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
P |
|
toLocal (position, from, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:58
Calculates the local position of the container relative to another point.
Name | Type | Attributes | Description |
---|---|---|---|
position | PointData | The world origin to calculate from. | |
from | Container | <optional> | The Container to calculate the global position from. |
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). |
skipUpdate | boolean | <optional> | Should we skip the update transform |
Type | Description |
---|---|
P |
|
updateCacheTexture () voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:70
Updates the cached texture. Will flag that this container's cached texture needs to be redrawn. This will happen on the next render.
updateLocalTransform () voidinherited
See scene_container_Container.ts.html:1163
Updates the local transform.
updateTransform (opts) thisinherited
See scene_container_Container.ts.html:1118
Updates the transform properties of the container (accepts partial values).
Name | Type | Description |
---|---|---|
opts | object | The options for updating the transform. |
opts.x | number | The x position of the container. |
opts.y | number | The y position of the container. |
opts.scaleX | number | The scale factor on the x-axis. |
opts.scaleY | number | The scale factor on the y-axis. |
opts.rotation | number | The rotation of the container, in radians. |
opts.skewX | number | The skew factor on the x-axis. |
opts.skewY | number | The skew factor on the y-axis. |
opts.pivotX | number | The x coordinate of the pivot point. |
opts.pivotY | number | The y coordinate of the pivot point. |
Type | Description |
---|---|
this |
zIndex (value)inherited
See scene_container_container-mixins_sortMixin.ts.html:42
The zIndex of the container.
Setting this value, will automatically set the parent to be sortable. Children will be automatically sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, and thus rendered on top of other display objects within the same container.
Name | Type | Description |
---|---|---|
value | number |
See: sortableChildren
_getGlobalBoundsRecursive (factorRenderLayers, bounds, currentLayer) voidinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:31
Recursively calculates the global bounds for the container and its children. This method is used internally by getFastGlobalBounds to traverse the scene graph.
Name | Type | Description |
---|---|---|
factorRenderLayers | boolean | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | The bounds object to update with the calculated values. |
currentLayer | IRenderLayer | The current render layer being processed. |
addChild (...children) Containerinherited
See scene_container_Container.ts.html:630
Adds one or more children to the container.
Multiple items can be added like so: myContainer.addChild(thingOne, thingTwo, thingThree)
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to add to the container |
Type | Description |
---|---|
Container |
|
addChildAt (child, index) Containerinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:151
Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown. If the child is already in this container, it will be moved to the specified index.
Name | Type | Description |
---|---|---|
child | Container | The child to add. |
index | number | The absolute index where the child will be positioned at the end of the operation. |
Type | Description |
---|---|
Container | The child that was added. |
addEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:681
Unlike on
or addListener
which are methods from EventEmitter, addEventListener
seeks to be compatible with the DOM's addEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event to listen to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | AddListenerOptions | <optional> | Listener options, used for capture phase. |
// Tell the user whether they did a single, double, triple, or nth click.
button.addEventListener('click', {
handleEvent(e): {
let prefix;
switch (e.detail) {
case 1: prefix = 'single'; break;
case 2: prefix = 'double'; break;
case 3: prefix = 'triple'; break;
default: prefix = e.detail + 'th'; break;
}
console.log('That was a ' + prefix + 'click');
}
});
// But skip the first click!
button.parent.addEventListener('click', function blockClickOnce(e) {
e.stopImmediatePropagation();
button.parent.removeEventListener('click', blockClickOnce, true);
}, {
capture: true,
});
cacheAsTexture (val) voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:13
Caches this container as a texture. This allows the container to be rendered as a single texture, which can improve performance for complex static containers.
Name | Type | Description |
---|---|---|
val | boolean | CacheAsTextureOptions | If true, enables caching with default options. If false, disables caching. Can also pass options object to configure caching behavior. |
collectRenderables (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:15
Collects all renderables from the container and its children, adding them to the instruction set. This method decides whether to use a simple or advanced collection method based on the container's properties.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesSimple (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:25
Collects renderables using a simple method, suitable for containers marked as simple. This method iterates over the container's children and adds their renderables to the instruction set.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
collectRenderablesWithEffects (instructionSet, renderer, currentLayer) voidinherited
See scene_container_container-mixins_collectRenderablesMixin.ts.html:35
Collects renderables using an advanced method, suitable for containers with complex processing needs. This method handles additional effects and transformations that may be applied to the renderables.
Name | Type | Description |
---|---|---|
instructionSet | InstructionSet | The set of instructions to which the renderables will be added. |
renderer | Renderer | The renderer responsible for rendering the scene. |
currentLayer | IRenderLayer | The current render layer being processed. |
disableRenderGroup () voidinherited
See scene_container_Container.ts.html:831
This will disable the render group for this container.
dispatchEvent (e) booleaninherited
See events_FederatedEventTarget.ts.html:772
Dispatch the event on this Container using the event's EventBoundary.
The target of the event is set to this
and the defaultPrevented
flag is cleared before dispatch.
Name | Type | Description |
---|---|---|
e | Event | The event to dispatch. |
Type | Description |
---|---|
boolean | Whether the preventDefault() method was not invoked. |
// Reuse a click event!
button.dispatchEvent(clickEvent);
enableRenderGroup () voidinherited
See scene_container_Container.ts.html:807
Calling this enables a render group for this container. This means it will be rendered as a separate set of instructions. The transform of the container will also be handled on the GPU rather than the CPU.
eventMode (value)inherited
See events_FederatedEventTarget.ts.html:601
Enable interaction events for the Container. Touch, pointer and mouse. There are 5 types of interaction settings:
'none'
: Ignores all interaction events, even on its children.'passive'
: (default) Does not emit events and ignores all hit testing on itself and non-interactive children. Interactive children will still emit events.'auto'
: Does not emit events but is hit tested if parent is interactive. Same asinteractive = false
in v7'static'
: Emit events and is hit tested. Same asinteraction = true
in v7'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
Name | Type | Description |
---|---|---|
value |
Since:
: - 7.2.0
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.on('tap', (event) => {
// Handle event
});
See scene_container_container-mixins_effectsMixin.ts.html:238
The area the filter is applied to. This is used as more of an optimization rather than figuring out the dimensions of the displayObject each frame you can set this rectangle.
Also works as an interaction mask.
Type | Description |
---|---|
Rectangle |
filters () readonlyinherited
See scene_container_container-mixins_effectsMixin.ts.html:191
Sets the filters for the displayObject. IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. To remove filters simply set this property to 'null'
.
Type | Description |
---|---|
readonly |
See scene_container_container-mixins_measureMixin.ts.html:111
Calculates and returns the (world) bounds of the display object as a Rectangle.
Name | Type | Attributes | Description |
---|---|---|---|
skipUpdate | boolean | <optional> | Setting to true will stop the transforms of the scene graph from being updated. This means the calculation returned MAY be out of date BUT will give you a nice performance boost. |
bounds | Bounds | <optional> | Optional bounds to store the result of the bounds calculation. |
Type | Description |
---|---|
Bounds |
|
getChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:100
Returns the child at the specified index
Name | Type | Description |
---|---|---|
index | number | The index to get the child at |
Type | Description |
---|---|
U |
|
getChildByLabel (label, deep) Containerinherited
See scene_container_container-mixins_findMixin.ts.html:66
Returns the first child in the container with the specified label.
Recursive searches are done in a pre-order traversal.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
Type | Description |
---|---|
Container | The child with the specified label. |
getChildByName (name, deep) ContainerDeprecated`` : since 8.0.0inherited
See scene_container_container-mixins_findMixin.ts.html:53
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
name | string | Instance name. | ||
deep | boolean | <optional> | false | Whether to search recursively |
See: getChildByLabel
Type | Description |
---|---|
Container | The child with the specified name. |
getChildIndex (child) numberinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:133
Returns the index position of a child Container instance
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The Container instance to identify |
Type | Description |
---|---|
number |
|
getChildrenByLabel (label, deep, out) Array<Container>inherited
See scene_container_container-mixins_findMixin.ts.html:103
Returns all children in the container with the specified label.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
label | string | RegExp | Instance label. | ||
deep | boolean | <optional> | false | Whether to search recursively |
out | Array<Container> | <optional> | [] | The array to store matching children in. |
Type | Description |
---|---|
Array<Container> | An array of children with the specified label. |
getFastGlobalBounds (factorRenderLayers, bounds) Boundsinherited
See scene_container_container-mixins_getFastGlobalBoundsMixin.ts.html:17
Computes an approximate global bounding box for the container and its children. This method is optimized for speed by using axis-aligned bounding boxes (AABBs), and uses the last render results from when it updated the transforms. This function does not update them. which may result in slightly larger bounds but never smaller than the actual bounds.
for accurate (but less performant) results use container.getGlobalBounds
Name | Type | Attributes | Description |
---|---|---|---|
factorRenderLayers | boolean | <optional> | A flag indicating whether to consider render layers in the calculation. |
bounds | Bounds | <optional> | The output bounds object to store the result. If not provided, a new one is created. |
Type | Description |
---|---|
Bounds | The computed bounds. |
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:15
Returns the global position of the container.
Name | Type | Default | Description |
---|---|---|---|
point | Point | The optional point to write the global value to. | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
Point |
|
See scene_container_container-mixins_measureMixin.ts.html:73
Retrieves the local bounds of the container as a Bounds object.
Type | Description |
---|---|
Bounds |
|
See scene_container_Container.ts.html:1059
Retrieves the size of the container as a Size object. This is faster than get the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
out | Size | <optional> | Optional object to store the size in. |
Type | Description |
---|---|
Size |
|
interactive (value)inherited
See events_FederatedEventTarget.ts.html:585
Enable interaction events for the Container. Touch, pointer and mouse
Name | Type | Description |
---|---|---|
value | boolean |
isCachedAsTexture () booleaninherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:46
Is this container cached as a texture?
Type | Description |
---|---|
boolean |
isInteractive () booleaninherited
See events_FederatedEventTarget.ts.html:631
Determines if the container is interactive or not
Since:
: - 7.2.0
Type | Description |
---|---|
boolean | Whether the container is interactive or not |
import { Sprite } from 'pixi.js';
const sprite = new Sprite(texture);
sprite.eventMode = 'static';
sprite.isInteractive(); // true
sprite.eventMode = 'dynamic';
sprite.isInteractive(); // true
sprite.eventMode = 'none';
sprite.isInteractive(); // false
sprite.eventMode = 'passive';
sprite.isInteractive(); // false
sprite.eventMode = 'auto';
sprite.isInteractive(); // false
mask () unknowninherited
See scene_container_container-mixins_effectsMixin.ts.html:110
Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. In PixiJS a regular mask must be a Graphics or a {@link Sprite} object. This allows for much faster masking in canvas as it utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. Otherwise, getLocalBounds
may calculate incorrect bounds, which makes the container's width and height wrong. To remove a mask, set this property to null
.
For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
Type | Description |
---|---|
unknown |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.mask = graphics;
See scene_container_container-mixins_onRenderMixin.ts.html:16
This callback is used when the container is rendered. This is where you should add your custom logic that is needed to be run every frame.
In v7 many users used updateTransform
for this, however the way v8 renders objects is different and "updateTransform" is no longer called every frame
Type | Description |
---|---|
(renderer: Renderer) => void |
const container = new Container();
container.onRender = () => {
container.rotation += 0.01;
};
removeChild (...children) Containerinherited
See scene_container_Container.ts.html:709
Removes one or more children from the container.
Name | Type | Description |
---|---|---|
children | Container | The Container(s) to remove |
Type | Description |
---|---|
Container | The first child that was removed. |
removeChildAt (index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:87
Removes a child from the specified index position.
Name | Type | Description |
---|---|---|
index | number | The index to get the child from |
Type | Description |
---|---|
U | The child that was removed. |
removeChildren (beginIndex, endIndex) ContainerChild[]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:29
Removes all children from this container that are within the begin and end indexes.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
beginIndex | number | 0 | The beginning position. | |
endIndex | number | <optional> | The ending position. Default value is size of the container. |
Type | Description |
---|---|
ContainerChild[] |
|
removeEventListener (type, listener, options)inherited
See events_FederatedEventTarget.ts.html:748
Unlike off
or removeListener
which are methods from EventEmitter, removeEventListener
seeks to be compatible with the DOM's removeEventListener
with support for options.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | The type of event the listener is bound to. | |
listener | EventListenerOrEventListenerObject | The listener callback or object. | |
options | RemoveListenerOptions | <optional> | The original listener options. This is required to deregister a capture phase listener. |
removeFromParent ()inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:249
Remove the Container from its parent Container. If the Container has no parent, do nothing.
reparentChild (...child) U[0]inherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:258
Reparent the child to this container, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
Type | Description |
---|---|
U[0] | The first child that was reparented. |
reparentChildAt (child, index) Uinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:276
Reparent the child to this container at the specified index, keeping the same worldTransform.
Name | Type | Description |
---|---|---|
child | U | The child to reparent |
index | number | The index to reparent the child to |
Type | Description |
---|---|
U |
setChildIndex (child, index) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:116
Changes the position of an existing child in the container
Name | Type | Description |
---|---|---|
child | ContainerChild | IRenderLayer | The child Container instance for which you want to change the index number |
index | number | The resulting index number for the child container |
setFromMatrix (matrix) voidinherited
See scene_container_Container.ts.html:1154
Updates the local transform using the given matrix.
Name | Type | Description |
---|---|---|
matrix | Matrix | The matrix to use for updating the transform. |
setMask (options)inherited
See scene_container_container-mixins_effectsMixin.ts.html:132
Used to set mask and control mask options.
Name | Type | Description |
---|---|---|
options | Partial<MaskOptionsAndMask> |
import { Graphics, Sprite } from 'pixi.js';
const graphics = new Graphics();
graphics.beginFill(0xFF3300);
graphics.drawRect(50, 250, 100, 100);
graphics.endFill();
const sprite = new Sprite(texture);
sprite.setMask({
mask: graphics,
inverse: true,
});
setSize (value, height)inherited
See scene_container_Container.ts.html:1081
Sets the size of the container to the specified width and height. This is faster than setting the width and height separately.
Name | Type | Attributes | Description |
---|---|---|---|
value | number | Optional<Size, "height"> | This can be either a number or a Size object. | |
height | number | <optional> | The height to set. Defaults to the value of width if not provided. |
swapChildren (child, child2) voidinherited
See scene_container_container-mixins_childrenHelperMixin.ts.html:221
Swaps the position of 2 Containers within this container.
Name | Type | Description |
---|---|---|
child | U | First container to swap |
child2 | U | Second container to swap |
toGlobal (position, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:37
Calculates the global position of the container.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
position | PointData | The world origin to calculate from. | ||
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). | |
skipUpdate | boolean | false | Should we skip the update transform. |
Type | Description |
---|---|
P |
|
toLocal (position, from, point, skipUpdate) Pinherited
See scene_container_container-mixins_toLocalGlobalMixin.ts.html:58
Calculates the local position of the container relative to another point.
Name | Type | Attributes | Description |
---|---|---|---|
position | PointData | The world origin to calculate from. | |
from | Container | <optional> | The Container to calculate the global position from. |
point | P | <optional> | A Point object in which to store the value, optional (otherwise will create a new Point). |
skipUpdate | boolean | <optional> | Should we skip the update transform |
Type | Description |
---|---|
P |
|
updateCacheTexture () voidinherited
See scene_container_container-mixins_cacheAsTextureMixin.ts.html:70
Updates the cached texture. Will flag that this container's cached texture needs to be redrawn. This will happen on the next render.
updateLocalTransform () voidinherited
See scene_container_Container.ts.html:1163
Updates the local transform.
updateTransform (opts) thisinherited
See scene_container_Container.ts.html:1118
Updates the transform properties of the container (accepts partial values).
Name | Type | Description |
---|---|---|
opts | object | The options for updating the transform. |
opts.x | number | The x position of the container. |
opts.y | number | The y position of the container. |
opts.scaleX | number | The scale factor on the x-axis. |
opts.scaleY | number | The scale factor on the y-axis. |
opts.rotation | number | The rotation of the container, in radians. |
opts.skewX | number | The skew factor on the x-axis. |
opts.skewY | number | The skew factor on the y-axis. |
opts.pivotX | number | The x coordinate of the pivot point. |
opts.pivotY | number | The y coordinate of the pivot point. |
Type | Description |
---|---|
this |
zIndex (value)inherited
See scene_container_container-mixins_sortMixin.ts.html:42
The zIndex of the container.
Setting this value, will automatically set the parent to be sortable. Children will be automatically sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, and thus rendered on top of other display objects within the same container.
Name | Type | Description |
---|---|---|
value | number |
See: sortableChildren
From class Container
click inherited
See events_EventBoundaryTypes.ts.html:120
Fired when a pointer device button (usually a mouse left-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
A click
event fires after the pointerdown
and pointerup
events, in that order. If the mouse is moved over another Container after the pointerdown
event, the click
event is fired on the most specific common ancestor of the two target Containers.
The detail
property of the event is the number of clicks that occurred within a 200ms window of each other upto the current click. For example, it will be 2
for a double click.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
clickcapture inherited
See events_EventBoundaryTypes.ts.html:136
Capture phase equivalent of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalmousemove inherited
See events_EventBoundaryTypes.ts.html:206
Fired when a pointer device (usually a mouse) is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalpointermove inherited
See events_EventBoundaryTypes.ts.html:391
Fired when a pointer device is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globaltouchmove inherited
See events_EventBoundaryTypes.ts.html:571
Fired when a touch point is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousedown inherited
See events_EventBoundaryTypes.ts.html:52
Fired when a mouse button (usually a mouse left-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The mousedown event. |
mousedowncapture inherited
See events_EventBoundaryTypes.ts.html:61
Capture phase equivalent of mousedown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The capture phase mousedown. |
mouseenter inherited
See events_EventBoundaryTypes.ts.html:249
Fired when the mouse pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseentercapture inherited
See events_EventBoundaryTypes.ts.html:257
Capture phase equivalent of mouseenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseleave inherited
See events_EventBoundaryTypes.ts.html:285
Fired when the mouse pointer exits a Container and its descendants.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent |
mouseleavecapture inherited
See events_EventBoundaryTypes.ts.html:293
Capture phase equivalent of mouseleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemove inherited
See events_EventBoundaryTypes.ts.html:215
Fired when a pointer device (usually a mouse) is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemovecapture inherited
See events_EventBoundaryTypes.ts.html:224
Capture phase equivalent of mousemove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseout inherited
See events_EventBoundaryTypes.ts.html:265
Fired when a pointer device (usually a mouse) is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This may be fired on a Container that was removed from the scene graph immediately after a mouseover
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseoutcapture inherited
See events_EventBoundaryTypes.ts.html:277
Capture phase equivalent of mouseout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseover inherited
See events_EventBoundaryTypes.ts.html:232
Fired when a pointer device (usually a mouse) is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseovercapture inherited
See events_EventBoundaryTypes.ts.html:241
Capture phase equivalent of mouseover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseup inherited
See events_EventBoundaryTypes.ts.html:86
Fired when a pointer device button (usually a mouse left-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupcapture inherited
See events_EventBoundaryTypes.ts.html:95
Capture phase equivalent of mouseup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutside inherited
See events_EventBoundaryTypes.ts.html:164
Fired when a pointer device button (usually a mouse left-button) is released outside the container that initially registered a mousedown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:179
Capture phase equivalent of mouseupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancel inherited
See events_EventBoundaryTypes.ts.html:335
Fired when the operating system cancels a pointer event. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancelcapture inherited
See events_EventBoundaryTypes.ts.html:344
Capture phase equivalent of pointercancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdown inherited
See events_EventBoundaryTypes.ts.html:301
Fired when a pointer device button is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdowncapture inherited
See events_EventBoundaryTypes.ts.html:310
Capture phase equivalent of pointerdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerenter inherited
See events_EventBoundaryTypes.ts.html:434
Fired when the pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerentercapture inherited
See events_EventBoundaryTypes.ts.html:442
Capture phase equivalent of pointerenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerleave inherited
See events_EventBoundaryTypes.ts.html:467
Fired when the pointer leaves the hit testing boundaries of a Container and its descendants.
This event notifies only the target and does not bubble.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The pointerleave event. |
pointerleavecapture inherited
See events_EventBoundaryTypes.ts.html:477
Capture phase equivalent of pointerleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermove inherited
See events_EventBoundaryTypes.ts.html:400
Fired when a pointer device is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermovecapture inherited
See events_EventBoundaryTypes.ts.html:409
Capture phase equivalent of pointermove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerout inherited
See events_EventBoundaryTypes.ts.html:450
Fired when a pointer device is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointeroutcapture inherited
See events_EventBoundaryTypes.ts.html:459
Capture phase equivalent of pointerout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerover inherited
See events_EventBoundaryTypes.ts.html:417
Fired when a pointer device is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerovercapture inherited
See events_EventBoundaryTypes.ts.html:426
Capture phase equivalent of pointerover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertap inherited
See events_EventBoundaryTypes.ts.html:352
Fired when a pointer device button is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertapcapture inherited
See events_EventBoundaryTypes.ts.html:361
Capture phase equivalent of pointertap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerup inherited
See events_EventBoundaryTypes.ts.html:318
Fired when a pointer device button is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupcapture inherited
See events_EventBoundaryTypes.ts.html:327
Capture phase equivalent of pointerup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutside inherited
See events_EventBoundaryTypes.ts.html:369
Fired when a pointer device button is released outside the container that initially registered a pointerdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:383
Capture phase equivalent of pointerupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclick inherited
See events_EventBoundaryTypes.ts.html:144
Fired when a pointer device secondary button (usually a mouse right-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event follows the semantics of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclickcapture inherited
See events_EventBoundaryTypes.ts.html:156
Capture phase equivalent of rightclick
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdown inherited
See events_EventBoundaryTypes.ts.html:69
Fired when a pointer device secondary button (usually a mouse right-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdowncapture inherited
See events_EventBoundaryTypes.ts.html:78
Capture phase equivalent of rightdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The rightdowncapture event. |
rightup inherited
See events_EventBoundaryTypes.ts.html:103
Fired when a pointer device secondary button (usually a mouse right-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupcapture inherited
See events_EventBoundaryTypes.ts.html:112
Capture phase equivalent of rightup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutside inherited
See events_EventBoundaryTypes.ts.html:187
Fired when a pointer device secondary button (usually a mouse right-button) is released outside the container that initially registered a rightdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:198
Capture phase equivalent of rightupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tap inherited
See events_EventBoundaryTypes.ts.html:536
Fired when a touch point is placed and removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tapcapture inherited
See events_EventBoundaryTypes.ts.html:545
Capture phase equivalent of tap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancel inherited
See events_EventBoundaryTypes.ts.html:519
Fired when the operating system cancels a touch. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancelcapture inherited
See events_EventBoundaryTypes.ts.html:528
Capture phase equivalent of touchcancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchend inherited
See events_EventBoundaryTypes.ts.html:502
Fired when a touch point is removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendcapture inherited
See events_EventBoundaryTypes.ts.html:511
Capture phase equivalent of touchend
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutside inherited
See events_EventBoundaryTypes.ts.html:553
Fired when a touch point is removed outside of the container that initially registered a touchstart. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:563
Capture phase equivalent of touchendoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmove inherited
See events_EventBoundaryTypes.ts.html:580
Fired when a touch point is moved along the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmovecapture inherited
See events_EventBoundaryTypes.ts.html:589
Capture phase equivalent of touchmove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstart inherited
See events_EventBoundaryTypes.ts.html:485
Fired when a touch point is placed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstartcapture inherited
See events_EventBoundaryTypes.ts.html:494
Capture phase equivalent of touchstart
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
wheel inherited
See events_EventBoundaryTypes.ts.html:597
Fired when a the user scrolls with the mouse cursor over a Container.
These events are propagating from the EventSystem.
- FederatedWheelEvent
wheelcapture inherited
See events_EventBoundaryTypes.ts.html:605
Capture phase equivalent of wheel
.
These events are propagating from the EventSystem.
- FederatedWheelEvent
click inherited
See events_EventBoundaryTypes.ts.html:120
Fired when a pointer device button (usually a mouse left-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
A click
event fires after the pointerdown
and pointerup
events, in that order. If the mouse is moved over another Container after the pointerdown
event, the click
event is fired on the most specific common ancestor of the two target Containers.
The detail
property of the event is the number of clicks that occurred within a 200ms window of each other upto the current click. For example, it will be 2
for a double click.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
clickcapture inherited
See events_EventBoundaryTypes.ts.html:136
Capture phase equivalent of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalmousemove inherited
See events_EventBoundaryTypes.ts.html:206
Fired when a pointer device (usually a mouse) is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globalpointermove inherited
See events_EventBoundaryTypes.ts.html:391
Fired when a pointer device is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
globaltouchmove inherited
See events_EventBoundaryTypes.ts.html:571
Fired when a touch point is moved globally over the scene. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousedown inherited
See events_EventBoundaryTypes.ts.html:52
Fired when a mouse button (usually a mouse left-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The mousedown event. |
mousedowncapture inherited
See events_EventBoundaryTypes.ts.html:61
Capture phase equivalent of mousedown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The capture phase mousedown. |
mouseenter inherited
See events_EventBoundaryTypes.ts.html:249
Fired when the mouse pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseentercapture inherited
See events_EventBoundaryTypes.ts.html:257
Capture phase equivalent of mouseenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseleave inherited
See events_EventBoundaryTypes.ts.html:285
Fired when the mouse pointer exits a Container and its descendants.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent |
mouseleavecapture inherited
See events_EventBoundaryTypes.ts.html:293
Capture phase equivalent of mouseleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemove inherited
See events_EventBoundaryTypes.ts.html:215
Fired when a pointer device (usually a mouse) is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mousemovecapture inherited
See events_EventBoundaryTypes.ts.html:224
Capture phase equivalent of mousemove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseout inherited
See events_EventBoundaryTypes.ts.html:265
Fired when a pointer device (usually a mouse) is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This may be fired on a Container that was removed from the scene graph immediately after a mouseover
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseoutcapture inherited
See events_EventBoundaryTypes.ts.html:277
Capture phase equivalent of mouseout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseover inherited
See events_EventBoundaryTypes.ts.html:232
Fired when a pointer device (usually a mouse) is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseovercapture inherited
See events_EventBoundaryTypes.ts.html:241
Capture phase equivalent of mouseover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseup inherited
See events_EventBoundaryTypes.ts.html:86
Fired when a pointer device button (usually a mouse left-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupcapture inherited
See events_EventBoundaryTypes.ts.html:95
Capture phase equivalent of mouseup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutside inherited
See events_EventBoundaryTypes.ts.html:164
Fired when a pointer device button (usually a mouse left-button) is released outside the container that initially registered a mousedown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
mouseupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:179
Capture phase equivalent of mouseupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancel inherited
See events_EventBoundaryTypes.ts.html:335
Fired when the operating system cancels a pointer event. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointercancelcapture inherited
See events_EventBoundaryTypes.ts.html:344
Capture phase equivalent of pointercancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdown inherited
See events_EventBoundaryTypes.ts.html:301
Fired when a pointer device button is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerdowncapture inherited
See events_EventBoundaryTypes.ts.html:310
Capture phase equivalent of pointerdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerenter inherited
See events_EventBoundaryTypes.ts.html:434
Fired when the pointer is moved over a Container and its descendant's hit testing boundaries.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerentercapture inherited
See events_EventBoundaryTypes.ts.html:442
Capture phase equivalent of pointerenter
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerleave inherited
See events_EventBoundaryTypes.ts.html:467
Fired when the pointer leaves the hit testing boundaries of a Container and its descendants.
This event notifies only the target and does not bubble.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The pointerleave event. |
pointerleavecapture inherited
See events_EventBoundaryTypes.ts.html:477
Capture phase equivalent of pointerleave
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermove inherited
See events_EventBoundaryTypes.ts.html:400
Fired when a pointer device is moved while over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointermovecapture inherited
See events_EventBoundaryTypes.ts.html:409
Capture phase equivalent of pointermove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerout inherited
See events_EventBoundaryTypes.ts.html:450
Fired when a pointer device is moved off the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointeroutcapture inherited
See events_EventBoundaryTypes.ts.html:459
Capture phase equivalent of pointerout
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerover inherited
See events_EventBoundaryTypes.ts.html:417
Fired when a pointer device is moved onto the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerovercapture inherited
See events_EventBoundaryTypes.ts.html:426
Capture phase equivalent of pointerover
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertap inherited
See events_EventBoundaryTypes.ts.html:352
Fired when a pointer device button is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointertapcapture inherited
See events_EventBoundaryTypes.ts.html:361
Capture phase equivalent of pointertap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerup inherited
See events_EventBoundaryTypes.ts.html:318
Fired when a pointer device button is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupcapture inherited
See events_EventBoundaryTypes.ts.html:327
Capture phase equivalent of pointerup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutside inherited
See events_EventBoundaryTypes.ts.html:369
Fired when a pointer device button is released outside the container that initially registered a pointerdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event is specific to the Federated Events API. It does not have a capture phase, unlike most of the other events. It only bubbles to the most specific ancestor of the targets of the corresponding pointerdown
and pointerup
events, i.e. the target of the click
event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
pointerupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:383
Capture phase equivalent of pointerupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclick inherited
See events_EventBoundaryTypes.ts.html:144
Fired when a pointer device secondary button (usually a mouse right-button) is pressed and released on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
This event follows the semantics of click
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightclickcapture inherited
See events_EventBoundaryTypes.ts.html:156
Capture phase equivalent of rightclick
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdown inherited
See events_EventBoundaryTypes.ts.html:69
Fired when a pointer device secondary button (usually a mouse right-button) is pressed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightdowncapture inherited
See events_EventBoundaryTypes.ts.html:78
Capture phase equivalent of rightdown
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | The rightdowncapture event. |
rightup inherited
See events_EventBoundaryTypes.ts.html:103
Fired when a pointer device secondary button (usually a mouse right-button) is released over the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupcapture inherited
See events_EventBoundaryTypes.ts.html:112
Capture phase equivalent of rightup
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutside inherited
See events_EventBoundaryTypes.ts.html:187
Fired when a pointer device secondary button (usually a mouse right-button) is released outside the container that initially registered a rightdown. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
rightupoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:198
Capture phase equivalent of rightupoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tap inherited
See events_EventBoundaryTypes.ts.html:536
Fired when a touch point is placed and removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
tapcapture inherited
See events_EventBoundaryTypes.ts.html:545
Capture phase equivalent of tap
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancel inherited
See events_EventBoundaryTypes.ts.html:519
Fired when the operating system cancels a touch. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchcancelcapture inherited
See events_EventBoundaryTypes.ts.html:528
Capture phase equivalent of touchcancel
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchend inherited
See events_EventBoundaryTypes.ts.html:502
Fired when a touch point is removed from the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendcapture inherited
See events_EventBoundaryTypes.ts.html:511
Capture phase equivalent of touchend
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutside inherited
See events_EventBoundaryTypes.ts.html:553
Fired when a touch point is removed outside of the container that initially registered a touchstart. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchendoutsidecapture inherited
See events_EventBoundaryTypes.ts.html:563
Capture phase equivalent of touchendoutside
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmove inherited
See events_EventBoundaryTypes.ts.html:580
Fired when a touch point is moved along the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchmovecapture inherited
See events_EventBoundaryTypes.ts.html:589
Capture phase equivalent of touchmove
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstart inherited
See events_EventBoundaryTypes.ts.html:485
Fired when a touch point is placed on the container. Container's eventMode
property must be set to static
or 'dynamic' to fire event.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
touchstartcapture inherited
See events_EventBoundaryTypes.ts.html:494
Capture phase equivalent of touchstart
.
These events are propagating from the EventSystem.
Name | Type | Description |
---|---|---|
event | FederatedPointerEvent | Event |
wheel inherited
See events_EventBoundaryTypes.ts.html:597
Fired when a the user scrolls with the mouse cursor over a Container.
These events are propagating from the EventSystem.
- FederatedWheelEvent
wheelcapture inherited
See events_EventBoundaryTypes.ts.html:605
Capture phase equivalent of wheel
.
These events are propagating from the EventSystem.
- FederatedWheelEvent
Options for creating a buffer
Name | Type | Default | Description |
---|---|---|---|
data | TypedArray | number[] | the data to initialize the buffer with, this can be a typed array, or a regular number array. If it is a number array, it will be converted to a Float32Array | |
label | string | a label for the buffer, this is useful for debugging | |
shrinkToFit | boolean | true | should the GPU buffer be shrunk when the data becomes smaller? changing this will cause the buffer to be destroyed and a new one created on the GPU this can be expensive, especially if the buffer is already big enough! setting this to false will prevent the buffer from being shrunk. This will yield better performance if you are constantly setting data that is changing size often. |
size | number | the size of the buffer in bytes, if not supplied, it will be inferred from the data | |
usage | number | the usage of the buffer, see BufferUsage |
dataTypedArray | number[]
the data to initialize the buffer with, this can be a typed array, or a regular number array. If it is a number array, it will be converted to a Float32Array
a label for the buffer, this is useful for debugging
should the GPU buffer be shrunk when the data becomes smaller? changing this will cause the buffer to be destroyed and a new one created on the GPU this can be expensive, especially if the buffer is already big enough! setting this to false will prevent the buffer from being shrunk. This will yield better performance if you are constantly setting data that is changing size often.
Default Value:
: - true
the size of the buffer in bytes, if not supplied, it will be inferred from the data
the usage of the buffer, see BufferUsage
Returns the 2D rendering context for the canvas. Caches the context after creating it.
The CollectRenderablesMixin interface defines methods for collecting renderable objects from a container and its children. These methods add the renderables to an instruction set, which is used by the renderer to process and display the scene.
Pixi supports multiple color formats, including CSS color strings, hex, numbers, and arrays.
When providing values for any of the color properties, you can use any of the ColorSource formats.
import { Color } from'pixi.js';
// All of these are valid:
sprite.tint = 'red';
sprite.tint = 0xff0000;
sprite.tint = '#ff0000';
sprite.tint = new Color('red');
// Same for graphics fill/stroke colors and other color values:
graphics.fill({ color: 'red' });
graphics.fill({ color: 0xff0000 });
graphics.stroke({ color: '#ff0000' });
graphics.stroke({ color: new Color('red')};
See color_Color.ts.html:38
Valid formats to use when defining any color properties, also valid for the Color constructor.
These types are extended from colord with some PixiJS-specific extensions.
Possible value types are:
- Color names:
'red'
,'green'
,'blue'
,'white'
, etc. - RGB hex integers (
0xRRGGBB
):0xff0000
,0x00ff00
,0x0000ff
, etc. - RGB(A) hex strings:
- 6 digits (
RRGGBB
):'ff0000'
,'#00ff00'
,'0x0000ff'
, etc. - 3 digits (
RGB
):'f00'
,'#0f0'
,'0x00f'
, etc. - 8 digits (
RRGGBBAA
):'ff000080'
,'#00ff0080'
,'0x0000ff80'
, etc. - 4 digits (
RGBA
):'f008'
,'#0f08'
,'0x00f8'
, etc.
- 6 digits (
- RGB(A) objects:
{ r: 255, g: 0, b: 0 }
,{ r: 255, g: 0, b: 0, a: 0.5 }
, etc. - RGB(A) strings:
'rgb(255, 0, 0)'
,'rgb(100% 0% 0%)'
,'rgba(255, 0, 0, 0.5)'
,'rgba(100% 0% 0% / 50%)'
, etc. - RGB(A) arrays:
[1, 0, 0]
,[1, 0, 0, 0.5]
, etc. - RGB(A) Float32Array:
new Float32Array([1, 0, 0])
,new Float32Array([1, 0, 0, 0.5])
, etc. - RGB(A) Uint8Array:
new Uint8Array([255, 0, 0])
,new Uint8Array([255, 0, 0, 128])
, etc. - RGB(A) Uint8ClampedArray:
new Uint8ClampedArray([255, 0, 0])
,new Uint8ClampedArray([255, 0, 0, 128])
, etc. - HSL(A) objects:
{ h: 0, s: 100, l: 50 }
,{ h: 0, s: 100, l: 50, a: 0.5 }
, etc. - HSL(A) strings:
'hsl(0, 100%, 50%)'
,'hsl(0deg 100% 50%)'
,'hsla(0, 100%, 50%, 0.5)'
,'hsla(0deg 100% 50% / 50%)'
, etc. - HSV(A) objects:
{ h: 0, s: 100, v: 100 }
,{ h: 0, s: 100, v: 100, a: 0.5 }
, etc. - Color objects.
Since:
: - 7.2.0
See color_Color.ts.html:30
RGBA color array.
[number, number, number, number]
Color utility class. Can accept any ColorSource format in its constructor.
import { Color } from'pixi.js';
new Color('red').toArray(); // [1, 0, 0, 1]new Color(0xff0000).toArray(); // [1, 0, 0, 1]new Color('ff0000').toArray(); // [1, 0, 0, 1]new Color('#f00').toArray(); // [1, 0, 0, 1]new Color('0xff0000ff').toArray(); // [1, 0, 0, 1]new Color('#f00f').toArray(); // [1, 0, 0, 1]new Color({ r: 255, g: 0, b: 0, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]new Color('rgb(255, 0, 0, 0.5)').toArray(); // [1, 0, 0, 0.5]new Color([1, 1, 1]).toArray(); // [1, 1, 1, 1]new Color([1, 0, 0, 0.5]).toArray(); // [1, 0, 0, 0.5]new Color(newFloat32Array([1, 0, 0, 0.5])).toArray(); // [1, 0, 0, 0.5]new Color(newUint8Array([255, 0, 0, 255])).toArray(); // [1, 0, 0, 1]new Color(newUint8ClampedArray([255, 0, 0, 255])).toArray(); // [1, 0, 0, 1]new Color({ h: 0, s: 100, l: 50, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]new Color('hsl(0, 100%, 50%, 50%)').toArray(); // [1, 0, 0, 0.5]new Color({ h: 0, s: 100, v: 100, a: 0.5 }).toArray(); // [1, 0, 0, 0.5]
See color_Color.ts.html:152
Name | Type | Default | Description |
---|---|---|---|
value | ColorSource | 0xffffff | Optional value to use, if not provided, white is used. |
Since:
: - 7.2.0
Default Color object for static uses
import { Color } from 'pixi.js';
Color.shared.setValue(0xffffff).toHex(); // '#ffffff'
Get alpha component (0 - 1)
Get blue component (0 - 1)
Get green component (0 - 1)
Get red component (0 - 1)
valueExclude<Color, ColorSource> | null
The current color source.
When setting:
- Setting to an instance of
Color
will copy its color source and components. - Otherwise,
Color
will try to normalize the color source and set the components. If the color source is invalid, anError
will be thrown and theColor
will left unchanged.
Note: The null
in the setter's parameter type is added to match the TypeScript rule: return type of getter must be assignable to its setter's parameter type. Setting value
to null
will throw an Error
.
When getting:
- A return value of
null
means the previous value was overridden (e.g., multiply, {@link Color.premultiply premultiply} or round). - Otherwise, the color source used when setting is returned.
isColorLike (value) value is ColorSourcestatic
See color_Color.ts.html:701
Check if the value is a color-like object
Name | Type | Description |
---|---|---|
value | unknown | Value to check |
Type | Description |
---|---|
value is ColorSource | True if the value is a color-like object |
import { Color } from 'pixi.js';
Color.isColorLike('white'); // returns true
Color.isColorLike(0xffffff); // returns true
Color.isColorLike([1, 1, 1]); // returns true
See color_Color.ts.html:466
Multiply with another color. This action is destructive, and will override the previous value
property to be null
.
Name | Type | Description |
---|---|---|
value | ColorSource | The color to multiply by. |
Type | Description |
---|---|
this |
See color_Color.ts.html:486
Converts color to a premultiplied alpha format. This action is destructive, and will override the previous value
property to be null
.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
alpha | number | The alpha to multiply by. | ||
applyToRGB | boolean | <optional> | true | Whether to premultiply RGB channels. |
Type | Description |
---|---|
Color |
|
See color_Color.ts.html:566
Set alpha, suitable for chaining.
Name | Type | Description |
---|---|---|
alpha | number |
Type | Description |
---|---|
this |
See color_Color.ts.html:188
Set the value, suitable for chaining
Name | Type | Description |
---|---|---|
value | ColorSource |
See: Color.value
Type | Description |
---|---|
this |
See color_Color.ts.html:375
Convert to an [R, G, B, A] array of normalized floats (numbers from 0.0 to 1.0).
Name | Type | Attributes | Description |
---|---|---|---|
out | Array<number> | Float32Array | <optional> | Output array |
Type | Description |
---|---|
T |
import { Color } from 'pixi.js';
new Color('white').toArray(); // returns [1, 1, 1, 1]
See color_Color.ts.html:439
Convert to a BGR number
Type | Description |
---|---|
number |
import { Color } from 'pixi.js';
new Color(0xffcc99).toBgrNumber(); // returns 0x99ccff
See color_Color.ts.html:539
Convert to a hexadecimal string.
Type | Description |
---|---|
string |
import { Color } from 'pixi.js';
new Color('white').toHex(); // returns "#ffffff"
See color_Color.ts.html:552
Convert to a hexadecimal string with alpha.
Type | Description |
---|---|
string |
import { Color } from 'pixi.js';
new Color('white').toHexa(); // returns "#ffffffff"
See color_Color.ts.html:452
Convert to a hexadecimal number in little endian format (e.g., BBGGRR).
Type | Description |
---|---|
number |
|
import { Color } from 'pixi.js';
new Color(0xffcc99).toLittleEndianNumber(); // returns 0x99ccff
See color_Color.ts.html:428
Convert to a hexadecimal number.
Type | Description |
---|---|
number |
import { Color } from 'pixi.js';
new Color('white').toNumber(); // returns 16777215
See color_Color.ts.html:509
Premultiplies alpha with current color.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
alpha | number | The alpha to multiply by. | ||
applyToRGB | boolean | <optional> | true | Whether to premultiply RGB channels. |
Type | Description |
---|---|
number | tint multiplied by alpha |
See color_Color.ts.html:327
Convert to a RGB color object.
Type | Description |
---|---|
RgbColor |
import { Color } from 'pixi.js';
new Color('white').toRgb(); // returns { r: 1, g: 1, b: 1 }
See color_Color.ts.html:314
Convert to a RGBA color object.
Type | Description |
---|---|
RgbaColor |
import { Color } from 'pixi.js';
new Color('white').toRgb(); // returns { r: 1, g: 1, b: 1, a: 1 }
See color_Color.ts.html:402
Convert to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0).
Name | Type | Attributes | Description |
---|---|---|---|
out | Array<number> | Float32Array | <optional> | Output array |
Type | Description |
---|---|
T |
import { Color } from 'pixi.js';
new Color('white').toRgbArray(); // returns [1, 1, 1]
See color_Color.ts.html:340
Convert to a CSS-style rgba string: rgba(255,255,255,1.0)
.
Type | Description |
---|---|
string |
See color_Color.ts.html:348
Convert to an [R, G, B] array of clamped uint8 values (0 to 255).
Name | Type | Attributes | Description |
---|---|---|---|
out | Array<number> | Uint8Array | Uint8ClampedArray | <optional> | Output array |
Type | Description |
---|---|
T |
import { Color } from 'pixi.js';
new Color('white').toUint8RgbArray(); // returns [255, 255, 255]
The DOMPipe class is responsible for managing and rendering DOM elements within a PixiJS scene. It maps dom elements to the canvas and ensures they are correctly positioned and visible.
See dom_DOMPipe.ts.html:34
Constructor for the DOMPipe class.
Name | Type | Description |
---|---|---|
renderer | Renderer | The renderer instance that this DOMPipe will be associated with. |
Static property defining the extension type and name for the DOMPipe. This is used to register the DOMPipe with different rendering pipelines.
See dom_DOMPipe.ts.html:55
Adds a renderable DOM container to the list of attached elements.
Name | Type | Description |
---|---|---|
domContainer | DOMContainer | The DOM container to be added. |
_instructionSet | InstructionSet | The instruction set (unused). |
See dom_DOMPipe.ts.html:144
Destroys the DOMPipe, removing all attached DOM elements and cleaning up resources.
See dom_DOMPipe.ts.html:87
Handles the post-rendering process, ensuring DOM elements are correctly positioned and visible.
See dom_DOMPipe.ts.html:68
Updates a renderable DOM container.
Name | Type | Description |
---|---|---|
_domContainer | DOMContainer | The DOM container to be updated (unused). |
See dom_DOMPipe.ts.html:77
Validates a renderable DOM container.
Name | Type | Description |
---|---|---|
_domContainer | DOMContainer | The DOM container to be validated (unused). |
Type | Description |
---|---|
boolean | Always returns true as validation is not required. |
PixiJS supports multiple environments including browsers, Web Workers, and Node.js. The environment is auto-detected by default using the environment.autoDetectEnvironment function.
The Adapter interface provides a way to abstract away the differences between these environments. PixiJS uses the BrowserAdapter by default.
However you can manually set the environment using the DOMAdapter singleton, for example to use Pixi within a WebWorker.
import { DOMAdapter, WebWorkerAdapter } from'pixi.js';
// WebWorkerAdapter is an implementation of the Adapter interface
DOMAdapter.set(WebWorkerAdapter);
// use the adapter to create a canvas (in this case an OffscreenCanvas)
DOMAdapter.get().createCanvas(800, 600);
This interface describes all the DOM dependent calls that Pixi makes throughout its codebase. Implementations of this interface can be used to make sure Pixi will work in any environment, such as browser, Web Workers, and Node.js.
Name | Type | Description |
---|---|---|
createCanvas | (width: number, height: number) => ICanvas | Returns a canvas object that can be used to create a webgl context. |
fetch | (url: RequestInfo, options: RequestInit) => Promise<Response> | Returns a Response object that has been fetched from the given URL. |
getBaseUrl | () => string | Returns the current base URL For browser environments this is either the document.baseURI or window.location.href |
getCanvasRenderingContext2D | () => { prototype : ICanvasRenderingContext2D } | Returns a 2D rendering context. |
getFontFaceSet | () => FontFaceSet | null | Return the font face set if available |
getNavigator | () => { userAgent : string, gpu : GPU | null } | Returns a partial implementation of the browsers window.navigator |
getWebGLRenderingContext | () => typeof WebGLRenderingContext | Returns a WebGL rendering context. |
parseXML | (xml: string) => Document | Returns Document object that has been parsed from the given XML string. |
Common interface for HTMLCanvasElement, OffscreenCanvas, and other custom canvas classes.
Name | Type | Description |
---|---|---|
height | number | Height of the canvas. |
parentNode | ICanvasParentNode | null | Parent node of the canvas. |
style | ICanvasStyle | Style of the canvas. |
width | number | Width of the canvas. |
Common interface for CanvasRenderingContext2D, OffscreenCanvasRenderingContext2D, and other custom canvas 2D context.
Name | Type | Description |
---|---|---|
letterSpacing | string | sets the horizontal spacing behavior between text characters. |
textLetterSpacing | string | sets the horizontal spacing behavior between text characters. |
This is an implementation of the Adapter interface. It can be used to make Pixi work in the browser.
Name | Type | Description |
---|---|---|
createCanvas | Function | Creates a canvas element of the given size. This canvas is created using the browser's native canvas element. |
fetch | Function | Returns a Response object that has been fetched from the given URL. |
getBaseUrl | Function | Returns the current base URL for browser environments this is either the document.baseURI or window.location.href |
getCanvasRenderingContext2D | Function | Returns a 2D rendering context. |
getFontFaceSet | Function | Return the font face set if available |
getNavigator | Function | Returns browsers window.navigator |
getWebGLRenderingContext | Function | Returns a WebGL rendering context. |
parseXML | Function | Returns Document object that has been parsed from the given XML string. |
Extension for the browser environment.
The DOMAdapter is a singleton that allows PixiJS to perform DOM operations, such as creating a canvas. This allows PixiJS to be used in any environment, such as a web browser, Web Worker, or Node.js. It uses the Adapter interface to abstract away the differences between these environments and uses the BrowserAdapter by default.
It has two methods: get():Adapter
and set(adapter: Adapter)
.
Defaults to the BrowserAdapter.
import { DOMAdapter, WebWorkerAdapter } from 'pixi.js';
// WebWorkerAdapter is an implementation of the Adapter interface
DOMAdapter.set(WebWorkerAdapter);
// use the adapter to create a canvas (in this case an OffscreenCanvas)
DOMAdapter.get().createCanvas(800, 600);
This is an implementation of the Adapter interface. It can be used to make Pixi work in a Web Worker.
Name | Type | Description |
---|---|---|
createCanvas | Function | Creates a canvas element of the given size using the browser's native OffscreenCanvas. |
fetch | Function | Returns a Response object that has been fetched from the given URL. |
getBaseUrl | Function | Returns the current base URL of the worker, which is globalThis.location.href |
getCanvasRenderingContext2D | Function | Returns a 2D rendering context. |
getFontFaceSet | Function | Return the font face set if available |
getNavigator | Function | Returns browsers window.navigator |
getWebGLRenderingContext | Function | Returns a WebGL rendering context. |
parseXML | Function | Returns Document object that has been parsed from the given XML string. |
Extension for the webworker environment.
This interface describes all the DOM dependent calls that Pixi makes throughout its codebase. Implementations of this interface can be used to make sure Pixi will work in any environment, such as browser, Web Workers, and Node.js.
Name | Type | Description |
---|---|---|
createCanvas | (width: number, height: number) => ICanvas | Returns a canvas object that can be used to create a webgl context. |
fetch | (url: RequestInfo, options: RequestInit) => Promise<Response> | Returns a Response object that has been fetched from the given URL. |
getBaseUrl | () => string | Returns the current base URL For browser environments this is either the document.baseURI or window.location.href |
getCanvasRenderingContext2D | () => { prototype : ICanvasRenderingContext2D } | Returns a 2D rendering context. |
getFontFaceSet | () => FontFaceSet | null | Return the font face set if available |
getNavigator | () => { userAgent : string, gpu : GPU | null } | Returns a partial implementation of the browsers window.navigator |
getWebGLRenderingContext | () => typeof WebGLRenderingContext | Returns a WebGL rendering context. |
parseXML | (xml: string) => Document | Returns Document object that has been parsed from the given XML string. |
Returns a canvas object that can be used to create a webgl context.
Returns a Response object that has been fetched from the given URL.
Returns the current base URL For browser environments this is either the document.baseURI or window.location.href
Returns a 2D rendering context.
Return the font face set if available
Returns a partial implementation of the browsers window.navigator
Returns a WebGL rendering context.
Returns Document object that has been parsed from the given XML string.
Common interface for HTMLCanvasElement, OffscreenCanvas, and other custom canvas classes.
Name | Type | Description |
---|---|---|
height | number | Height of the canvas. |
parentNode | ICanvasParentNode | null | Parent node of the canvas. |
style | ICanvasStyle | Style of the canvas. |
width | number | Width of the canvas. |
- PixiMixins.ICanvas
- Partial.<EventTarget>
Height of the canvas.
Parent node of the canvas.
Style of the canvas.
Width of the canvas.
See environment_canvas_ICanvas.ts.html:142
Adds the listener for the specified event.
Name | Type | Description |
---|---|---|
type | string | The type of event to listen for. |
listener | EventListenerOrEventListenerObject | The callback to invoke when the event is fired. |
options | boolean | AddEventListenerOptions | The options for adding event listener. |
See environment_canvas_ICanvas.ts.html:129
Get the content of the canvas as Blob.
Name | Type | Attributes | Description |
---|---|---|---|
options | object | <optional> | The options for creating Blob. |
options.type | string | <optional> | A string indicating the image format. The default type is image/png ; that type is also used if the given type isn't supported. |
options.quality | string | <optional> | A number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp ). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range. |
Type | Description |
---|---|
Promise<Blob> | A Promise returning a Blob object representing the image contained in the canvas. |
See environment_canvas_ICanvas.ts.html:180
Dispatches a event.
Name | Type | Description |
---|---|---|
event | Event | The Event object to dispatch. Its Event.target property will be set to the current EventTarget. |
Type | Description |
---|---|
boolean | Returns false if event is cancelable, and at least one of the event handlers which received event called Event.preventDefault(). Otherwise true. |
See environment_canvas_ICanvas.ts.html:194
Get the position and the size of the canvas.
Type | Description |
---|---|
ICanvasRect | The smallest rectangle which contains the entire canvas. |
See environment_canvas_ICanvas.ts.html:73
Get rendering context of the canvas.
Name | Type | Attributes | Description |
---|---|---|---|
contextId | ContextIds | The identifier of the type of context to create. | |
options | ContextSettings | <optional> | The options for creating context. |
Type | Description |
---|---|
RenderingContext | unknown | The created context, or null if contextId is not supported. |
See environment_canvas_ICanvas.ts.html:161
Removes the listener for the specified event.
Name | Type | Description |
---|---|---|
type | string | The type of event to listen for. |
listener | EventListenerOrEventListenerObject | The callback to invoke when the event is fired. |
options | boolean | EventListenerOptions | The options for removing event listener. |
See environment_canvas_ICanvas.ts.html:115
Creates a Blob from the content of the canvas.
Name | Type | Attributes | Description |
---|---|---|---|
callback | unknown | A callback function with the resulting Blob object as a single argument. null may be passed if the image cannot be created for any reason. |
|
type | string | <optional> | A string indicating the image format. The default type is image/png ; that type is also used if the given type isn't supported. |
quality | string | <optional> | A number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp ). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range. |
See environment_canvas_ICanvas.ts.html:103
Get the content of the canvas as data URL.
Name | Type | Attributes | Description |
---|---|---|---|
type | string | <optional> | A string indicating the image format. The default type is image/png ; that type is also used if the given type isn't supported. |
quality | string | <optional> | A number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp ). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range. |
Type | Description |
---|---|
string | A string containing the requested data URL. |
Common interface for CanvasRenderingContext2D, OffscreenCanvasRenderingContext2D, and other custom canvas 2D context.
Name | Type | Description |
---|---|---|
letterSpacing | string | sets the horizontal spacing behavior between text characters. |
textLetterSpacing | string | sets the horizontal spacing behavior between text characters. |
- CanvasState
- CanvasTransform
- CanvasCompositing
- CanvasImageSmoothing
- CanvasFillStrokeStyles
- CanvasShadowStyles
- CanvasFilters
- CanvasRect
- CanvasDrawPath
- CanvasText
- CanvasDrawImage
- CanvasImageData
- CanvasPathDrawingStyles
- Omit
- CanvasPath
sets the horizontal spacing behavior between text characters.
sets the horizontal spacing behavior between text characters.
See environment_canvas_ICanvasRenderingContext2D.ts.html:24
creates a pattern using the specified image and repetition.
Name | Type | Description |
---|---|---|
image | CanvasImageSource | ICanvas | |
repetition | string | null |
Type | Description |
---|---|
CanvasPattern | null |
See environment_canvas_ICanvasRenderingContext2D.ts.html:27
provides different ways to draw an image onto the canvas
Name | Type | Description |
---|---|---|
image | CanvasImageSource | ICanvas | |
dx | number | |
dy | number |
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.
The new event-based system that replaced InteractionManager from v6 has expanded the definition of what a Container means to be interactive. With this we have introduced eventMode
which allows you to control how an object responds to interaction events. This is similar to the interactive
property in v6 but with more options.
Enabling Interaction
Any Container-derived object (Sprite, Container, etc.) can become interactive simply by setting its eventMode
property to any of the EventMode values. 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 interaction example code.
Container-derived objects are based on EventEmitter3 so you can use on()
, once()
, off()
to listen to events.
For example to respond to clicks and taps, bind to an object ike so:
let sprite = Sprite.from('/some/texture.png');
sprite.eventMode = 'static'; // similar to `sprite.interactive = true` in v6
sprite.on('pointerdown', (event) => { alert('clicked!'); });
Check out the EventTypes section below for the full list of interaction events supported.
Event Modes
The new event-based system that replaced InteractionManager from v6 has expanded the definition of what a Container means to be interactive. With this we have introduced eventMode
which allows you to control how an object responds to interaction events. This is similar to the interactive
property in v6 but with more options.
event mode | Description |
---|---|
none | Ignores all interaction events, similar to CSS's pointer-events: none , good optimization for non-interactive children |
passive | Does not emit events and ignores hit testing on itself but does allow for events and hit testing only its interactive children. If you want to be compatible with v6, set this as your default eventMode (see options in Renderer, Application, etc) |
auto | Does not emit events and but is hit tested if parent is interactive. Same as interactive = false in v7 |
static | Emit 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. This is useful for elements that independently moving or animating. |
Event Types
Pixi supports the following event types for interactive objects:
Event Type | Fired When |
---|---|
pointercancel | Pointer device button is released outside the display object |
that initially registered a pointerdown. | |
pointerdown | Pointer device button is pressed on the display object. |
pointerenter | Pointer device enters the display object. |
pointerleave | Pointer device leaves the display object. |
pointermove | Pointer device is moved while over the display object. |
globalpointermove | Pointer device is moved, regardless of hit-testing the current object. |
pointerout | Pointer device is moved off the display object. |
pointerover | Pointer device is moved onto the display object. |
pointertap | Pointer device is tapped twice on the display object. |
pointerup | Pointer device button is released over the display object. |
pointerupoutside | Pointer device button is released outside the display object |
that initially registered a pointerdown. | |
mousedown | Mouse button is pressed on the display object. |
mouseenter | Mouse cursor enters the display object. |
mouseleave | Mouse cursor leaves the display object. |
mousemove | Mouse cursor is moved while over the display object. |
globalmousemove | Mouse is moved, regardless of hit-testing the current object. |
mouseout | Mouse cursor is moved off the display object. |
mouseover | Mouse cursor is moved onto the display object. |
mouseup | Mouse button is released over the display object. |
mouseupoutside | Mouse button is released outside the display object that initially registered a mousedown. |
click | Mouse button is clicked (pressed and released) over the display object. |
touchcancel | Touch point is removed outside of the display object that initially registered a touchstart. |
touchend | Touch point is removed from the display object. |
touchendoutside | Touch point is removed outside of the display object that initially registered a touchstart. |
touchmove | Touch point is moved along the display object. |
globaltouchmove | Touch point is moved, regardless of hit-testing the current object. |
touchstart | Touch point is placed on the display object. |
tap | Touch point is tapped twice on the display object. |
wheel | Mouse wheel is spun over the display object. |
rightclick | Right mouse button is clicked (pressed and released) over the display object. |
rightdown | Right mouse button is pressed on the display object. |
rightup | Right mouse button is released over the display object. |
rightupoutside | Right mouse button is released outside the display object that initially registered a rightdown. |
The event features that are enabled by the EventSystem (included in the pixi.js and pixi.js-legacy bundle), otherwise it will be ignored.
Name | Type | Description |
---|---|---|
click |
boolean | Enables pointer events associated with clicking:
|
globalMove |
boolean | Enables global pointer move events:
|
move |
boolean | Enables pointer events associated with pointer movement:
|
wheel |
boolean |
|
Since:
- 7.2.0
A simplified shape of an interactive object for the eventTarget
property of a FederatedEvent
Name | Type | Description |
---|---|---|
children | ReadonlyArray<FederatedEventTarget> | The children of this event target. |
isInteractive | () => boolean | Returns true if the Container has interactive 'static' or 'dynamic' |
parent | FederatedEventTarget | The parent of this event target. |
The properties available for any interactive object.
Name | Type | Description |
---|---|---|
cursor | Cursor | string | The cursor preferred when the mouse pointer is hovering over. |
eventMode | EventMode | The mode of interaction for this object |
hitArea | IHitArea | null | The hit-area specifies the area for which pointer events should be captured by this event target. |
interactive | boolean | Whether this event target should fire UI events. |
interactiveChildren | boolean | Whether this event target has any children that need UI events. This can be used optimize event propagation. |
onclick | FederatedEventHandler | null | Handler for 'click' event |
onglobalmousemove | FederatedEventHandler | null | Handler for 'globalmousemove' event |
onglobalpointermove | FederatedEventHandler | null | Handler for 'globalpointermove' event |
onglobaltouchmove | FederatedEventHandler | null | Handler for 'globaltouchmove' event |