Create an empty HTML file
We will start off by create a blank HTML page and an empty PixiJS application. Inside the new file, add this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PixiJS Moving objects</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.1.3/pixi.min.js"></script>
</head>
<body>
<script type="text/javascript">
// The application
var app = new PIXI.Application();
// Add application to the DOM
document.body.appendChild(app.view);
</script>
</body>
</html>
If you open up the HTML file in your browser, you should see a big black square. That means that the PixiJS application is working.
We are just using a CDN to import PixiJS, so we don't have to install anything. This is really easy to do, and it's more than enough for what we're doing in this tutorial.
Inside the <script> tag, we're creating a new Pixi application and adding it to the body.
Adding an object
In order to move an object, we need to see an object. We can make it really easy, and just add a red square. Below the line were the application is added to the body, add this code:
var square = new PIXI.Graphics();
square.beginFill(0xff0000);
square.drawRect(0, 0, 50, 50);
square.endFill();
square.x = 100;
square.y = 100;
app.stage.addChild(square);
In the first line, we define a new variable called square. This is a reference to the Graphics API from PixiJS. On the next line, we set the fill color to 0xff0000 (red). We then set the position and appending it to the stage.
If you open up the file you created in a browser, a small red square will appear.
Making the object move
The next thing we need to do is to add this line below the line where we append the square to the stage:
requestAnimationFrame(update);
You're not ready to see the result yet, we need to create the update function. Below this line, add this code:
function update() {
square.position.x += 1;
app.render(app.stage);
requestAnimationFrame(update);
}
This is the function where everything happens. For every possible update (60 times per second, 60 fps), this function will be called. There's a couple of different ways to to this, but "requestAnimationFrame" is really easy to use.
Every time the function is called, we add one pixel to the x position of the square. But the line below "app.render(app.stage);" is equally important, because this redraws the entire canvas every time.
I hope this was interesting. Try to play around with more objects and options like rotation, scale, etc. If you have any questions, feel free to leave a reply below.