preface

My main reason for writing this article is that most of the basic pixiJS tutorials on the web have various problems and are not suitable for getting started or getting started. This article is written by combining my reference materials with the official website documents to ensure that the written examples are directly available; If there is any mistake, I hope to point out, thank you!

Pixijs profile

It’s official: It’s a Canvas based 2D WebGL rendering engine that can create rich interactive graphics, animations and games. Pixi aims to provide a fast, lightweight, all-device compatible 2D library that allows developers to enjoy hardware acceleration without WebGL knowledge. It uses WebGL rendering by default, but gracefully degrades to Canvas rendering if the browser doesn’t support it. Full mouse and touch events are also supported for drawing content.

I summarize the characteristics:

  • Support WebGL rendering, because can call GPU rendering, so high rendering performance
  • Support for Canvas rendering. Canvas rendering is automatically used when the device does not support WebGL, or you can manually select Canvas rendering
  • Very simple to use drawing Api, provides a lot of encapsulated methods
  • Rich interactive events, support for complete mouse and mobile touch events

.

Now let’s write the code…

I’m going to put a picture here, and I’m going to use it later

Pixijs drawing begins

Pixijs has several important classes:

  • View (UI, see view)
  • Container (Stage, scene)
  • Renderer
  • Ticker
  • Loader (resource Loader)
  • Sprite

The view and render

A view can be instantiated to multiple DOM elements

So what about Renderer?

There are two kinds of PixiJS renderers, one is pixi. WebGLRenderer, which is drawn with WebGL, and the other is pixi. CanvasRenderer, which is drawn with canvas

The source address

Look at this example:


<! DOCTYPEhtml>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pixijs</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/pixi.js/5.3.8/pixi.min.js"></script>
</head>
<style>
  body {
    height: 100vh;
    width: 100vw;
  }
</style>

<body>
  <div id="canvas1"></div>
  <div id="canvas2"></div>
 
  <script>
    const app = new PIXI.Application({
      width: 400.height: 400.antialias: true.transparent: false.backgroundColor: 0xFF33CCFF.// Hexadecimal
    });

    document.getElementById('canvas1').appendChild(app.view); // App. view is an HTMLCanvasElement

    // app.renderer.backgroundColor = 0x00CC99;



    const app1 = new PIXI.Application({
      width: 400.height: 400.antialias: true.transparent: false.backgroundColor: 0xff0000});document.getElementById('canvas2').appendChild(app1.view);


  
  </script>
</body>

</html>
 
Copy the code

New Pixi.application () is used to instantiate PIXI. There are two ways to instantiate PIXI:

    // Create it directly
    const app = new PIXI.Application();
    document.body.appendChild(app.view);
Copy the code
   // Select the element (see the example above)
    const app = new PIXI.Application({
      view: document.getElementById('canvas1')});Copy the code

Container (Stage, scene)

API address: API

Let me just draw a picture of what it is. Okay?

App. stage is an instance of a Container. As the lowest level of the stage, all graphics to be rendered must be placed inside the Container to be displayed.

Pixi.container has some features:

  • Can be added to other components and element index operation, such as new setting depth and sort (container. SortableChildren = true)
  • Non-interactive by default, interaction can be set, various listeners can be used (mouse events, etc.) (container.interactive = true;)
  • You can set x, Y, alpha, setTransform, etc

Here’s an example (draw an image with the image at the top) :

 <! DOCTYPEhtml>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pixijs</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/pixi.js/5.3.8/pixi.min.js"></script>

</head>
<style>
  body {
    height: 100vh;
    width: 100vw;
  }
</style>

<body>

  <canvas id="main"></canvas>

  <script>
    const app = new PIXI.Application({
      view: document.getElementById('main'),
      width: 1000.height: 1000.antialias: true.transparent: false.backgroundColor: 0xFF33CCFF});const container = new PIXI.Container();

    // Container also has its own x and y positions
    app.stage.addChild(container);  // Generally, a custom container is created
    
   

    // Load the texture
    const img = PIXI.Texture.from('./he.jpg'); // Your image address
    // Add the texture to the Sprite. Only the Sprite can set its own properties
    const bunny = new PIXI.Sprite(img);
    bunny.x = app.screen.width / 2;
    bunny.y = app.screen.height / 2;
    bunny.zIndex = 1;
    bunny.anchor.set(0.5);


    // // this can be multiple images, such as images from the network or local load finished rendering
    // const loader = new PIXI.Loader();
    // loader
    // .add('img1', './he.jpg')
    // .load((loader, resource) => {
    // console.log('Done');
    // for (let prop in resource) {
    // const sprite = new PIXI.Sprite(resource[prop].texture);
    // sprite.x = 10;
    // sprite.y = 10;
    // sprite.width = 200;
    // sprite.height = 200;
    // sprite.zIndex = 1;
    / / / / Sprite. Anchor. Set (0.5)
    // container.addChild(sprite)
    / /}
    / /})

    // Don't forget to add it to the container
    container.addChild(bunny);


  </script>
</body>

</html>
Copy the code

๐Ÿงš came ๏ธ Sprite

API address: API

Container has been used in the previous section. Here is a diagram to illustrate the relationship:

Note: ๐Ÿงšโ™€๏ธ : pixi.sprite () and text: pixi.textStyle () are two important APIS for graphics.pixi.graphics ().

Ticker

API address: API

Ticker is similar to setInterval, setTimeout, requestAnimationFrame, etc.

Some of the more important apis:

  • add
  • addOnce
  • destroy
  • start
  • stop
  • update

Look at an example (image at top)

 <! DOCTYPEhtml>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pixijs</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/pixi.js/5.3.8/pixi.min.js"></script>
</head>
<style>
  body {
    height: 100vh;
    width: 100vw;
  }
</style>

<body>

  <canvas id="main"></canvas>


  </div>
  <script>
    const app = new PIXI.Application({
      view: document.getElementById('main'),
      width: 1000.height: 1000.antialias: true.transparent: false.backgroundColor: 0xFF33CCFF});const container = new PIXI.Container();
    app.stage.addChild(container);

    // Wait for the image to load
    const loader = new PIXI.Loader();
    loader
      .add('fakeimg'.'./21.jpg')  // Your image address
      .load((loader, resource) = > {
        console.log('Done');
        init(resource);
      })
    function init(item) {
      const sprite = new PIXI.Sprite(item.fakeimg.texture);
      container.addChild(sprite);
    }


    app.ticker.add((delta) = > {
      container.x += 2;
      container.y += 2;
    })

 
  </script>
</body>

</html>
 
Copy the code

But you see, the picture is not moving, so let’s do a better collision detection, let’s make it move back and forth


   <! DOCTYPEhtml>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pixijs</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/pixi.js/5.3.8/pixi.min.js"></script>
</head>
<style>
  body {
    height: 100vh;
    width: 100vw;
  }
</style>

<body>

  <canvas id="main"></canvas>


  </div>
  <script>
    const app = new PIXI.Application({
      view: document.getElementById('main'),
      width: 1000.height: 1000.antialias: true.transparent: false.backgroundColor: 0xFF33CCFF});const container = new PIXI.Container();
    app.stage.addChild(container);

    const loader = new PIXI.Loader();
    loader
      .add('fakeimg'.'./21.jpg')
      .load((loader, resource) = > {
        console.log('Done');
        init(resource);
      })
    function init(item) {
      const sprite = new PIXI.Sprite(item.fakeimg.texture);
      container.addChild(sprite);
    }

    let status = 1;

    app.ticker.add((delta) = > {
      // container.x += 2;
      // container.y += 2;
      tickerLoop()
    })

    function tickerLoop() {
      if (status) {
        container.x += 5;
        container.y += 5;
        if (container.x > 800) {
          status = 0; }}else {
        container.x -= 5;
        container.y -= 5;
        if (container.x < 0) {
          status = 1; }}}</script>
</body>

</html>
Copy the code

Pixijs event interaction

  • Compatible with common trigger of mouse and touch screen

type InteractionPointerEvents = “pointerdown” | “pointercancel” | “pointerup” | “pointertap” | “pointerupoutside” | “pointermove” | “pointerover” | “pointerout”;

  • Touch screen trigger event

Touchcancel type InteractionTouchEvents = “touchstart” | “” |” touchend “|” touchendoutside “|” touchmove “|” tap “;

  • Mouse trigger event

type InteractionMouseEvents = “rightdown” | “mousedown” | “rightup” | “mouseup” | “rightclick” | “click” | “rightupoutside” | “mouseupoutside” | “mousemove” | “mouseover” | “mouseout”;

Here’s an example:

   <! DOCTYPEhtml>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pixijs</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/pixi.js/5.3.8/pixi.min.js"></script>

</head>
<style>
  body {
    height: 100vh;
    width: 100vw;
  }
</style>

<body>

  <canvas id="main"></canvas>



  <script>
    const app = new PIXI.Application({
      view: document.getElementById('main'),
      width: 1000.height: 1000.antialias: true.transparent: false.backgroundColor: 0xFF33CCFF});const container = new PIXI.Container();

    app.stage.addChild(container);

    // Load the texture
    const img = PIXI.Texture.from('./21.jpg'); // The picture is at the top
    // Add texture to Sprite. Only sprites can set various properties
    const imgSprite = new PIXI.Sprite(img);
    imgSprite.x = app.screen.width / 2;
    imgSprite.y = app.screen.height / 2;
    imgSprite.anchor.set(0.5);
    
    // Don't forget to add it to the container
    container.addChild(imgSprite);

    // Don't forget this sentence
    imgSprite.interactive = true;
 
 
    // Listen on events
    imgSprite
      .on('pointerdown', onDragStart)
      .on('pointermove', onDragMove)
      .on('pointerup', onDragEnd)
      .on('pointerupoutside', onDragEnd)


    function onDragStart(event) {
       
      this.data = event.data;
      this.alpha = 0.5;
      this.dragging = true;
     
    }

    function onDragEnd() {
      this.alpha = 1;
      this.dragging = false;
      this.data = null;

    }

    function onDragMove() {
      if (this.dragging) {
        const newPosition = this.data.getLocalPosition(this.parent);
        this.x = newPosition.x;
        this.y = newPosition.y; }}</script>
</body>

</html>
Copy the code

Pixijs operation events are not very different from ordinary ones, so check out the official demo

The last

The above examples are handwritten by myself, hoping to be helpful for learning and using. I will write some in-depth things later, thank you!

Happy Mid-Autumn Festival! ๐Ÿงจ ๐ŸŽ‡

Links:

Pixjs official [pixijs.com/]

[pixjs demo] (pixijs. IO/examples /)