React PIXI pt.2 — Viewport

Jason
2 min readNov 6, 2020

--

Introduction

In part II of the React PIXI series we’ll be taking a look at how to implement a viewport using pixi-viewport. So what is a viewport? It’s something that will allow us to zoom and pan our 2d canvas. More specifically it’s:

A highly configurable viewport/2D camera designed to work with pixi.js.

Features include dragging, pinch-to-zoom, mouse wheel zooming, decelerated dragging, follow target, animate, snap to point, snap to zoom, clamping, bouncing on edges, and move on mouse edges.

Initial Setup

Just like in part I, we’ll start with a simple stage populated with the pixi bunny sprite.

We’ll need pixi-viewport so let’s go ahead and install that.

npm i pixi-viewport

Creating the Viewport Component

If you take a look at pixi-viewport’s documentation you will see that it’s pretty easy to implement a viewport in JavaScript. The problem is we’re working within React, which complicates the implementation. We need to somehow turn the viewport into a React component. Luckily, the React PIXI library is robust enough to handle such implementations. They were forward thinking enough to allow for custom components which we will use.

Start by creating a Viewport.tsx file within your src directory. Next we’ll use React-PIXI’s PixiComponent to create our custom component. We can plug in pixi-viewport’s simple example code within the create value of PixiComponent. It should look like this:

As you can see from the code, we’re expecting to receive three props within PixiComponentViewport: width, height, and app. Width and height will set the size of the screen. App is a reference to the PIXI.Application instance. Within React PIXI, the PIXI.Application instance is provided by <Stage/>. And we can get a reference to that instance using React PIXI’s useApp hook. There’s just one problem. PixiComponent is not a React component, it just returns one. And that is important because you’re only allowed to use react hooks within React components. So how are we supposed to access the PIXI.Application instance if we can’t use the useApp hook? We’ll need a wrapper component to handle that.

We can create a wrapper component that is a React component. Within it, we can use the useApp hook, then pass it to PixiComponentViewport as a prop:

Adding the Viewport to Stage

Now that we have created a custom viewport component we need to add it to stage. It’ll be a child of stage, and essentially be the new “stage”. So rather than adding PIXI objects to stage, we’ll add them to viewport. That way everything exists within the viewport and can be panned/zoomed. I went ahead and added more bunny sprites so it’s easier to see how the panning and zooming works within the viewport. Just click and drag to pan, and use the scroll to zoom in and out.

--

--