Introduction to PIXI - PIXI document translation (1)

1. Create the Renderer and Stage The
first step is to create a rectangular display area on which you can start displaying images. Pixi has a renderer object to create this for you. It automatically generates an HTML <canvas> element and calculates how to display your image on the canvas. Then you need to create a special Pixi Container object called stage. As you will see, this stage object will be used as the root container for everything you want Pixi to display.

Here is the code you need to write to create the renderer and stage. Add this code between the <script> tags of your HTML document:
//Create the renderer
var renderer = PIXI.autoDetectRenderer (256, 256);

//Add the canvas to the HTML document
document.body.appendChild(renderer.view);

//Create a container object called the `stage`
var stage = new PIXI.Container();

//Tell the `renderer` to `render` the `stage`
renderer.render(stage);

This is the most basic code you need to write to get started with Pixi. It generates a black 256px by 256px canvas element and adds it to your HTML document. Here is what is displayed in the browser when running this code.

Yay, a black square!

Pixi's autoDetectRenderer method determines whether to use the Canvas drawing API or WebGL to render the graphics, depending on what's available. Its first and second parameters are the width and height of the canvas. However, you can include an optional third parameter along with some additional values ​​that can be set. This third parameter is an object literal, here's how to use it to set antialiasing, transparency and resolution:
renderer =  PIXI。autoDetectRenderer(
   256,256,
  {antialias : false,transparent: false,resolution: 1 }
);


The third parameter (the options object) is optional - if you're happy with Pixi's default settings, you can drop it, usually you don't need to change them. (However, see Pixi's documentation on Canvas Renderer and WebGLRenderer for more information if needed.)

What do these options do?
{antialias: false, transparent: false, resolution: 1}

antialias smooths the edges of fonts and graphics primitives. (WebGL antialiasing is not available on all platforms, so you need to test this feature on the target platform of your game.) transparent makes the canvas background transparent. resolution makes it easier to use displays of different resolutions and pixel densities. Setting resolution is a bit beyond the scope of this tutorial, but check out Mat Grove's explanation on how to use resolution for all the details. But generally, just keep resolution at 1 for most projects and you'll be fine.

(Note: the renderer has an additional, fourth option preserveDrawingBuffer, which defaults to false. The only reason to set it to true is if you need to call Pixi's specialized dataToURL method on a WebGL canvas context).

Pixi's renderer objects use WebGL by default, which is good because WebGL is incredibly fast and lets you use some spectacular visual effects that you'll learn all about in the future. But if you need to force the Canvas drawing API to render via WebGL, you can do this:
renderer = new PIXI.CanvasRenderer(256, 256);


Only the first two parameters are required: width and height.

You can force WebGL to render like this:
renderer = new PIXI.WebGLRenderer(256, 256);


The renderer.view object is just a plain old plain <canvas> object, so you can control it the same way you would control any other canvas object. Here's how to give the canvas an optional dashed border:

renderer.view.style.border = "1px dashed black";


If you need to change the background color of the canvas after creation, set the backgroundColor property of the renderer object to any hex color value:
renderer.backgroundColor = 0x061639;


If you want to find the width or height of the renderer, use renderer.view.width and renderer.view.height.

(Important: Although stage also has width and height properties, they don't refer to the size of the rendering window. Stage's width and height just tell you the area occupied by what you put inside it - more up front!)

To change the canvas size, use the renderer's' resize method, and provide any new values ​​for width and height. However, to ensure that the canvas is resized to match the resolution, set autoResize to true.
renderer.autoResize = true;
renderer.resize(512, 512);

If you want the canvas to fill the entire window, you can apply this CSS style and resize the renderer to the size of the browser window.
renderer.view.style.position = "absolute";
renderer.view.style.display = "block";
renderer.autoResize = true;
renderer.resize(window.innerWidth, window.innerHeight);


However, if you do, make sure you also set the default padding and margin to 0 on all HTML elements with this bit of CSS code:

<style> *{ padding:0;margin:0 } </style>


(The asterisk * in the code above is the CSS "universal selector", it just means "all tags in the HTML document").

If you want the canvas to scale proportionally to any browser window size, you can use this custom scaleToWindow function.

2. Pixi Sprite
In the previous section, you learned how to create a stage object as follows:
var stage =  new  PIXI.Container();


The stage is Pixi's Container object. You can think of a container as an empty box that will hold together and store whatever you put inside. The stage object we create is the root container for everything visible in your scene. Pixi requires you to have a root container object because the renderer needs to render things:
renderer.render(stage);


Whatever you put inside the stage will be rendered on the canvas. Right now the stage is empty, but soon we'll start putting stuff in it.

(note: you can give your root container any name you like, call it scene or root if you like the name stage is just an old but useful convention we will stick to in this tutorial)

then what do you put in stage superior? Special image objects are called sprites. Sprites are basically just pictures that you can control with code. You can control their position, size and other properties useful for making interactive and animated graphics. Learning to make and control sprites is really the most important thing, learning to use Pixi. If you know how to make sprites and add them to the stage, you're just one small step to start making a game.

Pixi has a Sprite class that is a versatile way to make game sprites. There are three main ways to create them:

(1) From a single image file.
(2) From the subimage on the tile. A tileset is a single big picture that includes all the pictures you need in your game.
(3) From a texture atlas (a JSON file that defines the size and location of the image set).

You'll learn all three methods, but before you do, let's understand what images you need to know before you can display them with Pixi.

Loading the image into the texture cache
Because Pixi uses WebGL to render images on the GPU, the images need to be in a format that the GPU can handle. WebGL-ready images are called textures. Before making the sprite display the image, you need to convert the normal image file to a WebGL texture. To keep everything working fast and efficiently under the hood, Pixi uses a texture cache to store and reference all the textures your sprites will need. The names of textures are strings that match the file locations of the images they refer to. This means that if you have a texture load "images/cat.png", you can find it in the texture cache like this:

PIXI.utils.TextureCache["images/cat.png"];


Textures are stored in a WebGL compatible format, which is valid for the Pixi renderer to work with. Then you can use Pixi's Sprite class to create a new sprite with the texture.

var texture = PIXI.utils.TextureCache["images/anySpriteImage.png"];
var sprite = new PIXI.Sprite(texture);


But how to load the image file and convert it to texture? Use Pixi's built-in loader object.

Pixi's powerful loader object is all you need to load any type of image. Here's how to use it to load an image and call the setup function that is called after the image is loaded:

PIXI.loader
  .add("images/anyImage.png")
  .load(setup);

function setup() {
  //This code will run when the loader has finished loading the image
}

The PIXI development team recommends that if you use a loader, you should create the sprite loader's resources object by referencing the texture, like this:
var sprite = new PIXI.Sprite (
  PIXI.loader.resources["images/anyImage.png"].texture
);

Here is some complete code example you can write to load an image, call the setup function, and create a sprite from the loaded image:
PIXI.loader
  .add("images/anyImage.png")
  .load(setup);

function setup() {
  var sprite = new PIXI.Sprite (
    PIXI.loader.resources["images/anyImage.png"].texture
  );
}


You can load multiple images by listing them using the chainable add method, like this:
PIXI.loader
  .add("images/imageOne.png")
  .add("images/imageTwo.png")
  .add("images/imageThree.png")
  .load(setup);


Better yet, just list all the files you want to load into an array in a single add method, like this:

PIXI.loader
  .add([
    "images/imageOne.png",
    "images/imageTwo.png",
    "images/imageThree.png"
  ])
  .load(setup);


The loader also lets you load JSON files, which you will learn about later.

3. After displaying the sprites
load the image and use it to make the sprite, there are two more things you need to do before you can see it on the canvas:

-1. You need to add sprites to Pixi's stage with the stage.addChild method, as follows:

stage.addChild(cat);

The stage is the main container for all sprites.

-2. You need to tell Pixi's renderer to render the stage.

renderer.render(stage);

Your sprite won't show until you do both of these things.

Before we go any further, let's look at a practical example of how to display a single image using what we just learned. In the examples/images folder you will find a 64x64 pixel PNG image of a cat.


Here is all the JavaScript code you need to load the image, create a sprite, and display it on the Pixi stage:

var stage = new PIXI.Container(),
    renderer = PIXI.autoDetectRenderer(256, 256);
document.body.appendChild(renderer.view);

//Use Pixi's built-in `loader` object to load an image
PIXI.loader
  .add("images/cat.png")
  .load(setup);

//This `setup` function will run when the image has loaded
function setup() {

  //Create the `cat` sprite from the texture
  var cat = new PIXI.Sprite(
    PIXI.loader.resources["images/cat.png"].texture
  );

  //Add the cat to the stage
  stage.addChild(cat);

  //Render the stage   
  renderer.render(stage);
}


When you run this code, you will see the following:



Now we are here!
If you need to remove a sprite from the stage, use the removeChild method:
stage.removeChild(anySprite)

But usually setting the sprite's visible property to false will be an easier and more efficient way to make the sprites disappear.
anySprite.visible = false;


Using Aliases
You can save yourself some typing and make your code more readable by creating short-form aliases for Pixi objects and methods that you use frequently. For example, PIXI.utils.TextureCache typing too much? I think so, especially on a big project, you can use it dozens of times. So, create a shorter alias to point to it, like this:
var TextureCache = PIXI.utils.TextureCache

Then, use the alias instead of the original, like this:
var texture = TextureCache["images/cat.png"];

Besides letting you write more concise code, using aliases has an added benefit: it helps to slightly buffer your Pixi's frequently changing API. If Pixi's API changes in a future version - it will! - You just need to update these aliases to Pixi objects and methods in one place, at the beginning of the program, not per instance, and they are used throughout the code. So when the Pixi development team decides they want to rearrange the furniture, you're one step ahead of them!

To see how to do this, let's rewrite the code we wrote to load an image and display it, using aliases for all Pixi objects and methods.

//Aliases
var Container = PIXI.Container,
    autoDetectRenderer = PIXI.autoDetectRenderer,
    loader = PIXI.loader,
    resources = PIXI.loader.resources,
    Sprite = PIXI.Sprite;

//Create a Pixi stage and renderer and add the
//renderer.view to the DOM
var stage = new Container (),
    renderer = autoDetectRenderer(256, 256);
document.body.appendChild(renderer.view);

//load an image and run the `setup` function when it's done
loader
  .add("images/cat.png")
  .load(setup);

function setup() {

  //Create the `cat` sprite, add it to the stage, and render it
  var cat = new Sprite(resources["images/cat.png"].texture);  
  stage.addChild(cat);
  renderer.render(stage);
}


Most of the examples in this tutorial will use aliases for Pixi objects that follow this same model. Unless otherwise stated, you can assume that all code samples use aliases like this.

That's all you need to know to start loading images and creating sprites.

4. A little bit about loading progress

The format I showed above is what I recommend you use as a standard template for loading images and displaying sprites. So, you can safely ignore the next few paragraphs and skip directly to the next section, "Locating sprites." But Pixi's loader object is quite complex and includes some functions that you should be aware of, even if you don't use them regularly. Let's look at some of the most useful ones.

Creating sprites from plain JavaScript Image objects or Canvas

For optimization and efficiency, it's best to create sprites from textures that have been preloaded into Pixi's texture cache. But if for some reason you need to create a texture from a regular JavaScript Image object, you can use the Pixi BaseTexture and Texture classes:
var base = new PIXI.BaseTexture (anyImageObject),
    texture = new PIXI.Texture(base),
    sprite = new PIXI.Sprite(texture);


You can use BaseTexture.fromCanvas if you want to make a texture from any existing canvas element:

var base = new PIXI.BaseTexture.fromCanvas(anyCanvasElement),


If you want to change the texture the sprite is displaying, use the texture property. Set it to any Texture object like this:
anySprite.texture = PIXI.utils.TextureCache["anyTexture.png"];



You can use this technique to interactively change the appearance of the sprite if something major happens in the game.

Specifying a name for the load file

You can assign a unique name to each resource to be loaded. Just provide the name (string) as the first parameter in the add method. For example, here's how to name a cat image catImage.

PIXI.loader
  .add("catImage", "images/cat.png")
  .load(setup);


This will create an object called catImage in loader.resources. This means you can create sprites by referencing the catImage object like this:

var cat = new PIXI.Sprite(PIXI.loader.resources.catImage.texture);


However, I recommend that you do not use this feature! This is because you have to remember all the names you gave each loaded file, as well as make sure you don't accidentally use the same name multiple times. Using file pathnames, like we did in the previous example, is more error prone.

Monitoring Load Progress

Pixi's loader has a special progress event that will call a customizable function that runs every time a file is loaded. The progress event is called on the loader's on method, like this:
PIXI.loader.on("progress", loadProgressHandler);

Here's how to include the on method in the load chain and call a user-definable function in loadProgressHandler every time a file is loaded
PIXI.loader.on("progress", loadProgressHandler);


PIXI.loader
  .add([
    "images/one.png",
    "images/two.png",
    "images/three.png"
  ])
  .on("progress", loadProgressHandler)
  .load(setup);

function loadProgressHandler() {
  console.log("loading");
}

function setup() {
  console.log("setup");
}


Every time one of the files is loaded, the progress event will call loadProgressHandler to display "loading" in the console. When all three files are loaded, the setup function will run. Here is the output of the above code in the console:
loading
loading
loading
setup


It's neat, but it gets better. You can also determine exactly what files have been loaded and what percentage of files are currently loaded. You can do this by adding optional loader and resource parameters to loadProgressHandler, like this:

function loadProgressHandler(loader, resource) { //...

Then you can use resource.url to find the currently loaded file. (resource.name If you want to find an optional name that may have been assigned to the file, use this option as the first argument to the method add.) You can use loader.progress to find the percentage of total resources currently loaded. Here is some code.

PIXI.loader
  .add([
    "images/one.png",
    "images/two.png",
    "images/three.png"
  ])
  .on("progress", loadProgressHandler)
  .load(setup);

function loadProgressHandler(loader, resource) {

  //Display the file `url` currently being loaded
  console.log("loading: " + resource.url);

  //Display the precentage of files currently loaded
  console.log("progress: " + loader.progress + "%");

  //If you gave your files names as the first argument
  //of the `add` method, you can access them like this
  //console.log("loading: " + resource.name);
}

function setup() {
  console.log("All files loaded");
}


Here's what the code looks like in the console when it runs:
loading: images/one.png
progress: 33.333333333333336%
loading: images/two.png
progress: 66.66666666666667%
loading: images/three.png
progress: 100%
All files loaded


This is really cool because you can use it as a basis for creating a loading progress bar.

(Note: you can access other properties of the resource object resource.error will tell you any possible errors that occurred when trying to load the file, and resource.data gives you access to the file's raw binary data.)

More on Pixi's loader

Pixi's The loader is ridiculously feature-rich and configurable. Let's take a quick look at its usage to get you started.

The chainable add method of the loader requires 4 basic parameters:
add(name, url, optionObject, callbackFunction)

Here's a description of these parameters in the loader's source code documentation:

name (string): The name of the resource to load. If not passed, the url is used.
url (string): The url of this resource, relative to the baseUrl loader.
options (object literal): options to load.
options.crossOrigin (Boolean): Is the request cross-origin? The default value is determined automatically.
options.loadType: How should the resource be loaded? The default value is Resource.LOAD_TYPE.XHR.
options.xhrType: How should the loaded data be interpreted when using XHR? Default is Resource.XHR_RESPONSE_TYPE.DEFAULT
callbackFunction : The function to call when this particular resource has finished loading.

The only required of these parameters is the url (the file to load).

Below are some examples of ways you can use the add method to load files. The first of these are what the documentation calls the "normal syntax" of a loader:
.add('key', 'http://...', function () {})
.add('http://...', function () {})
.add('http://...')


These are examples of "object syntax" for loaders:

.add({
  name: 'key2',
  url: 'http://...'
}, function () {})

.add({
  url: 'http://...'
}, function () {})

.add({
  name: 'key3',
  url: 'http://...'
  onComplete: function () {}
})

.add({
  url: 'https://...',
  onComplete: function () {},
  crossOrigin: true
})


You can also pass an add object or an array of urls or both to the method:
.add([
  {name: 'key4', url: 'http://...', onComplete: function () {} },
  {url: 'http://...', onComplete: function () {} },
  'http://...'
]);


(Note: If you need to reset the loader to load a new batch file, call the loader's reset method: PIXI.loader.reset();)

Pixi's loader has more advanced features, including options that allow you to Load and parse all types of binaries. This is not a day job you need to do and is beyond the scope of this tutorial, so make sure to check out the loader's GitHub repository for more information.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326308521&siteId=291194637