How to Append Pixi.js Canvas to HTML Body
To render graphics in your web browser using Pixi.js, you must add its rendering surface to your web page. This article provides a straightforward guide on how to initialize a Pixi.js application and append its automatically generated canvas element directly to the HTML document body using JavaScript.
Step 1: Initialize the Pixi.js Application
First, you need to create and initialize an instance of the Pixi.js
Application. This setup creates the renderer, the ticker,
and the root container.
For Pixi.js v8 (the latest version), the initialization is asynchronous:
import { Application } from 'pixi.js';
// Create a new application
const app = new Application();
// Initialize the application with options
await app.init({ width: 800, height: 600, backgroundColor: 0x1099bb });For Pixi.js v7 and earlier, the initialization is synchronous:
// Create the application instance directly (v7 and older)
const app = new PIXI.Application({ width: 800, height: 600, backgroundColor: 0x1099bb });Step 2: Append the Canvas to the Document Body
Once the application is initialized, Pixi.js generates a standard
HTML <canvas> element. You can target the HTML
<body> and insert this canvas using the standard DOM
method appendChild().
The property used to access the canvas element depends on the version of Pixi.js you are using:
For Pixi.js v8:
In version 8, the canvas element is accessed via the
app.canvas property.
// Append the canvas element to the HTML body
document.body.appendChild(app.canvas);For Pixi.js v7 and Earlier:
In version 7 and below, the canvas element is accessed via the
app.view property.
// Append the canvas element to the HTML body
document.body.appendChild(app.view);Complete Implementation Example (Pixi.js v8)
Here is a complete, minimal HTML and JavaScript example demonstrating the entire process:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pixi.js Canvas Setup</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #000;
}
</style>
</head>
<body>
<script type="module">
import { Application } from 'https://cdn.jsdelivr.net/npm/pixi.js@8.x/dist/pixi.min.mjs';
async function setup() {
// Initialize Pixi.js
const app = new Application();
await app.init({ resizeTo: window });
// Append the canvas to the document body
document.body.appendChild(app.canvas);
}
setup();
</script>
</body>
</html>