sequence

As a serious front-end developer, in order to survive must find a way to improve their ability!!

Want to learn some new knowledge that can be connected with the front end, want to do a small game that can run on the Web to practice hand (), even if not improve ability also have to improve their vision, although the technology may not get old, developers pain O (╥﹏╥) O

Times have changed

The actual skyfighter (I, as I will probably be called later) had already been learning something about it. At present, if you want to do some small games on the Web, it is basically HTML games now, after all, Flash has been phased out, times have changed. At the beginning of the web page above a lot of small games are based on Flash development, such as the famous half bottle of fairy vinegar this developer is the development of a lot of Flash games.

Flash is familiar to anyone who has ever touched the Internet, regardless of age, for example, early online video, Flash animation and web version of small games are inseparable from its support. Until today, a lot of web site content still needs through Flash plugin to show, there’s a train system website before should be Flash outage events are fire (dalian train operation depot, research recovery for train running day and night, but it is not security, privacy, incomplete termination process service features also always let a person.

At the beginning of the 4399 and so on the small game website is also in constant transformation, from the era of Flash come out, or quite miss the former “death VS Fire” and so on the small game.

Flash gone: Adobe officially announced the end of support for Flash on December 31, 2020. Adobe will not release any updates or security patches for Flash after this date. In addition, Adobe will remove all archives of earlier versions of Flash Player from its official website and block Flash-based content from running.

Learning options

The general learning process is as follows: Understand relevant game background knowledge and terminology (understanding scenes (pages), Sprite (controls), timelines (timers), etc.) understand specific languages and IDES, as well as game engines such as DOM, Cocos, etc

In fact, in some front-end game development today, the choice is nothing more than that. For the empty city machine this amateur, just start from the simple JS library. Then you’ll learn about Cocos Creator. In HTML, the entry js library is probably a few options, although the empty city machine before three. Js hill, but pixi.js hill empty city machine is also ready to visit, after all, 3D doors always look bigger than 2D.

If you are interested in the three. Js series, please check it out.

A Miscellany of Three.Js (I) — Starting

.

A Miscellany of Three.js (11) — Elves and Particles (Drawing a Map of China)

Because not a student, the reason to go to work during the day, directly to work to learn too arrogant, so first from the document slowly start to learn it!

Advice found online:

If you don't use a game engine. Write native HTML, JS, CSS, or canvas/ SVG. If you're using a game engine and want to use a technology stack on the front end, use Cocos Creator. One development, multiple packaging. The whole engine is very much like Unity 3D, which is a 2D version of Unity. Js is used as the scripting language. Cocos Creator can only do 2D games for now. If you want to make 3d games. So let's go straight to Unity3d. Although Unity3d also supports js as a scripting language, in fact most companies and teams choose C# and most tutorials use C# as a scripting language, so if you want to learn Unity3d, you need to learn C#Copy the code

The text start

Front of the nonsense water a lot of words it L (T﹏T)┛

Next up is the main dish about pixi……





What is Pixi.js?

Official note: The aim of this project is to provide a fast lightweight 2D library that works across all devices. The PixiJS renderer allows everyone to enjoy the power of hardware acceleration without prior knowledge of WebGL. Also, it’s fast. Really fast.

原 文 : The goal of this project is to provide a fast and lightweight 2D library that works across all devices. The PixiJS renderer allows everyone to enjoy the power of hardware acceleration without prior knowledge of WebGL. And it’s fast. It’s really fast.

Pixi.js is a lightweight 2D library that can be used for HTML action rendering, and because it works with WebGL, we don’t have to worry about the performance of pixi.js. Pixi.js is very fast.

Here’s another, more comprehensive introduction to Pixi (copied, of course) :


Pixi is a very fast 2D Sprite rendering engine. What does that mean? That means it can help you display, animate, and manage interactive graphics so you can easily make games and apps using JavaScript and other HTML5 technologies. It has a reasonable, clean API and includes many useful features such as support for texture atlases and providing a streamlined system for animated sprites (interactive images). It also gives you a complete scene diagram so you can create hierarchies of nested sprites (sprites within sprites) and allows you to attach mouse and touch events directly to sprites. And, most importantly, Pixi gives you the freedom to use it, adapt it to your personal coding style, and integrate seamlessly with other frameworks.

The Pixi API was actually first used by Macromedia/Adobe Flash and has been tested and improved repeatedly, making it easy for Flash developers to use. Current rendering frameworks that use similar apis include CreateJS, Starling, Sparrow, and Apple’s SpriteKit. The strength of the Pixi API is its versatility: it’s not a game engine. This is great for users, because you have complete freedom to use it to make whatever you like, even to build your own game engine.


Here are two useful websites for learning pixi.js:

PixiJS API Document

Pixi. Js Chinese website

The Chinese language is very convenient for us to learn, but there is a disadvantage, times have changed, some methods of Pixi described in Chinese language may have changed, if we download the latest version of pixi.js, then we may not use these methods (just like the air city computer learned three.

So another API website is particularly important. Although the API website is in English, which is very, very unfriendly for learners like me who are not good at English, it can find the latest methods. So I accept the imperfections of English, life is like…… You can’t fight it. You just have to accept it.

How do I get started?

After finding the reference tutorial, then we will follow the tutorial to slowly learn up.

First

First, let’s download pixi.js and install it.

GitHub repository address: github.com/pixijs/pixi…

The pixi.js file can be obtained from the repository and imported using the script tag

<script src="pixi.min.js"></script>
Copy the code

But since I created a Vue CLI project, I chose to use NPM for the download. The download statement is also very simple, note that you need to add.js to the end of pixi. After downloading pixi.js, I did not find the pixi in package.json. It was actually downloaded.

npm install pixi.js
Copy the code

Let’s test with the following code to see if pixi.js has been imported.

Vue project, write in main.js to test.


import * as PIXI from 'pixi.js'
Vue.use(PIXI)
/ * * * * * * * * * * * if you are using a script tag, don't need the above two sentences * * * * * * * * * * * * * * * /
// Test whether pixi is installed successfully
let type = "WebGL"
if(! PIXI.utils.isWebGLSupported()){ type ="canvas"
}
PIXI.utils.sayHello(type)
Copy the code

F12 opens the console of the page and finds that PixiJS is successfully used and tells you the current version of PixiJS. The Chinese version is PixiJS 4.4.5.

Second

Import pixi.js tool, so hurry up to build the stage, with the stage, the characters can come on stage

Pixi.js to build the scene is also in the above, which I think we are not strange

Create an environment:

Create a rectangular display area using the Application object on the Pixi. It automatically generates an HTML < Canvas > element and displays the image on the Canvas canvas. Pixi. Application will automatically choose to use Canvas or WebGL to render graphics, depending on your browser support. Pixi. Application has an Options object. In this case, its width and height properties are used to set the width and height in pixels of the Canvas Canvas. You can set more optional properties in the Options object; Here’s how to use it to set anti-aliasing, transparency, and resolution.

<template>
  <div id="pixi1"></div>
</template>

<script>
    // var pixi = require('pixi');  
    import * as pixi from 'pixi.js'

    export default {
        name: "pixi1".props: {},
        data() {
            return {};
        },
        mounted() {
            this.initState();
        },
        methods: {
            initState() {
                //Create a Pixi Application
                let app = new pixi.Application({
                    width: 300.// Default: 300 width
                    height: 300.// default: 300 height
                    antialias: true.// default: false Anti-aliasing
                    transparent: true.// default: false transparency
                    resolution: 1 ,      // default: 1 resolution
                    backgroundAlpha: 0.// Set the opacity of the background color to 0
                    // Since WebGL is very fast, the renderer object in Pixi will default to WebGL. If you want to use the Canvas Drawing API, you can set the forceCanvas option to true
                    forceCanvas: false
                });
                console.log(app)
                // Add the canvas to the element
                document.getElementById('pixi1').appendChild(app.view)
            }
        }
    };
</script>
<style scoped>
</style>
Copy the code

This generates a transparent Canvas tag that is 300 pixels wide and high

Generated pixi:

Of course, to make it easier to see, let’s make the background colored, renderer. BackgroundColor

let app = new pixi.Application({
  width: 300.// Default: 800 width
  height: 300.// Default: the height is 600
  antialias: true.// default: false Anti-aliasing
  transparent: false.// default: false transparency
  resolution: 1.// default: 1 resolution
  backgroundAlpha: 0   // Set the opacity of the background color to 0
});
app.renderer.backgroundColor = 0x8b968d;  // Set the canvas background color
Copy the code

Effect:

If you need to cover the stage full screen, then widen to set the canvas size and listen for deformation

initState() {
  //Create a Pixi Application
  let app = new pixi.Application({
    width: 300.// Default: 800 width
    height: 300.// Default: the height is 600
    antialias: true.// default: false Anti-aliasing
    transparent: false.// default: false transparency
    resolution: 1.// default: 1 resolution
    backgroundAlpha: 0   // Set the opacity of the background color to 0
  });
  console.log(app)
  app.renderer.backgroundColor = 0x8b968d;  // Set the canvas background color
  // App. view is a Canvas canvas that generates a black canvas element 256 pixels by 256 pixels
  document.getElementById('pixi1').appendChild(app.view)
  app.renderer.view.style.position = "absolute";
  app.renderer.view.style.display = "block";
  app.renderer.autoResize = true;  // To make sure the canvas is resized to match the resolution
  app.renderer.resize(window.innerWidth, window.innerHeight);    // Change the stage size
  window.onresize = function () {
    app.renderer.resize(window.innerWidth, window.innerHeight);
  } 
  // Stage is a stage. Stage is Pixi's Container object
  console.log(app.stage)
}
Copy the code

Effect:

There are many other properties created by pixi.js, which are not listed here, but need to be used to check the API documentation

Third

There is a stage, so the characters will also appear!

Anything you want visible in the renderer must be added to a special Pixi object called stage. This is app.stage up here and you can print it out.

Stage is Pixi’s Container object. You can think of a Container as a kind of empty box that puts things together and stores them. The stage object is the root container for all visible objects in the scene. Anything you put in the stage will be rendered on the Canvas. Right now the stage is empty, but soon we’ll start putting things in.

The performers, or people, on the stage are called sprites. A special image object of this kind. You can control their location, size, and other properties.

There are three ways to create it:

  • Through a single image file.

  • Through Sprite.

  • Through texture mapping.

I have an article about how to create a texture map: TexturePacker

I’m going to write a quick code here because I’m sleepy.

This is a collection of texture stickers generated by TexturePacker, baokemeng1.json.

The generated JSON mainly shows that it is composed of three pictures, the specific material I threw to the net disk, interested can download: pan.baidu.com/s/1A-BsG_5h…

Extraction code: GJHI

The location information is explained in JSON, which is also the basis for judging and tailoring characters and scenes

"anim.png":
{
	"frame": {"x":212."y":1."w":50."h":88},
	"rotated": false."trimmed": true."spriteSourceSize": {"x":0."y":2."w":50."h":88},
	"sourceSize": {"w":50."h":90}},"changjing.png":
{
	"frame": {"x":1."y":1."w":209."h":214},
	"rotated": false."trimmed": false."spriteSourceSize": {"x":0."y":0."w":209."h":214},
	"sourceSize": {"w":209."h":214}},"damu2.png":
{
	"frame": {"x":212."y":91."w":56."h":87},
	"rotated": false."trimmed": true."spriteSourceSize": {"x":0."y":0."w":56."h":87},
	"sourceSize": {"w":60."h":90}}},Copy the code

Without further ado, let’s see what happens

It’s you, Code beast. Let’s go

<template>
    <div id="pixi4"></div>
</template>

<script>
import * as pixi from 'pixi.js'

function keyboard(value) {
  let key = {};
  key.value = value;
  key.isDown = false;
  key.isUp = true;
  key.press = undefined;
  key.release = undefined;
  //The `downHandler`
  key.downHandler = event= > {
    if (event.key === key.value) {
      if (key.isUp && key.press) key.press();
      key.isDown = true;
      key.isUp = false; event.preventDefault(); }};//The `upHandler`
  key.upHandler = event= > {
    if (event.key === key.value) {
      if (key.isDown && key.release) key.release();
      key.isDown = false;
      key.isUp = true; event.preventDefault(); }};//Attach event listeners
  const downListener = key.downHandler.bind(key);
  const upListener = key.upHandler.bind(key);
  
  window.addEventListener(
    "keydown", downListener, false
  );
  window.addEventListener(
    "keyup", upListener, false
  );
  
  // Detach event listeners
  key.unsubscribe = () = > {
    window.removeEventListener("keydown", downListener);
    window.removeEventListener("keyup", upListener);
  };
  
  return key;
}

export default {
    name: "pixi4".components: {},
    props: {},
    data() {
        return {
            loader: null
        };
    },
    created() {},
    mounted() {
        this.initState();
    },
    watch: {},
    computed: {},
    methods: {
        initState() {
            this.loader = new pixi.Loader();
            let Rectangle = pixi.Rectangle; 
            //Create a Pixi Application
            let app = new pixi.Application({
                width: window.innerWidth,         // Default: 800 width
                height: window.innerHeight,        // Default: the height is 600
                antialias: true.// default: false Anti-aliasing
                Transparent: true, // default: false
                resolution: 1 ,      // default: 1 resolution
                backgroundAlpha: 0   // Set the opacity of the background color to 0
            });

            document.getElementById('pixi4').appendChild(app.view)
            app.renderer.view.style.display = "block";
            app.renderer.autoResize = true;  
            window.onresize = function () {
                app.renderer.resize(window.innerWidth, window.innerHeight);
            }
            // Load the texture map, create sprites, and add sprites to the stage
            let src2 = "./img/baokemeng1.json";
            this.loader.add([{name:'huo'.url: src}, {name:'damu'.url: src2}]).load(() = >{
                let textures = this.loader.resources.damu.textures; 
                / / the scene
                let changjingsprite = this.setTexture(textures["changjing.png"])
                app.stage.addChild(changjingsprite);
                // Cut out the characters
                let rectangle = new Rectangle(229.1.16.7.22);
                let texture = textures["anim.png"];
                texture.frame = rectangle;
                let damu = this.setTexture(texture)
                app.stage.addChild(damu);
                // Scene size and location
                changjingsprite.scale.set(2.2);
                changjingsprite.x = 100
                // Big wood in scene size, position
                damu.width = 33;
                damu.height = 44;
                damu.x = 220;
                damu.y = 180;
                damu.vx = 0;
                damu.vy = 0;
                
                // The big wood moves
                app.ticker.add(() = > this.gameLoop(damu));
                this.keyMove(damu);
            })
            
            // Listen for SRC load events
            this.loader.onProgress.add((loader, resource) = > {
                // console.log(" Current progress: ", loader.progress, "%");
                // console.log(resource.url)
            });
            this.loader.onError.add(() = > {
                console.log("Failed to load image or JSON")}); },keyMove(person) {
            let left = keyboard('a'), up = keyboard('w'), right = keyboard('d'), down = keyboard('s');
            left.press = () = > {
                person.vx = -1;
                person.vy = 0;
            };
            left.release = () = > {
                person.vx = 0;
                person.vy = 0;
            };
            right.press = () = > {
                person.vx = 1;
                person.vy = 0;
            };
            right.release = () = > {
                person.vx = 0;
                person.vy = 0;
            };
            up.press = () = > {
                person.vx = 0;
                person.vy = -2;
            };
            up.release = () = > {
                person.vx = 0;
                person.vy = 0;
            };
            down.press = () = > {
                person.vx = 0;
                person.vy = 2;
            };
            down.release = () = > {
                person.vx = 0;
                person.vy = 0;
            };
        },
        gameLoop(person){
            //Move the cat 1 pixel 
            person.x += person.vx;
            person.y += person.vy;
        },
        setTexture (texture) {
            // console.log(texture)
            let sprite = new pixi.Sprite(texture);
            returnsprite; ,}}};</script>
<style scoped>
</style>
Copy the code

Effect:

Whew, it’s over!

Ha ha ha, finally completed the first pixi.js learning record