Skip to main content

入门

¥Getting Started

在本节中,我们将构建最简单的 PixiJS 应用。在此过程中,我们将逐步介绍如何构建和提供代码的基础知识。

¥In this section we're going to build the simplest possible PixiJS application. In doing so, we'll walk through the basics of how to build and serve the code.

高级用户

¥Advanced Users

在我们开始之前先简单说明一下:本指南针对的是那些在开发基于 JavaScript 的应用方面经验很少的 PixiJS 初级开发者。如果你是一位编码老手,你可能会发现这里的详细程度没有帮助。如果是这种情况,你可能需要浏览一下本指南,然后像 webpack 和 npm 一样跳入 如何使用 PixiJS 和加壳器

¥A quick note before we start: this guide is aimed at beginning PixiJS developers who have minimal experience developing JavaScript-based applications. If you are a coding veteran, you may find that the level of detail here is not helpful. If that's the case, you may want to skim this guide, then jump into how to work with PixiJS and packers like webpack and npm.

关于 JavaScript 的注意事项

¥A Note About JavaScript

最后一点。JavaScript 世界目前正在从老式 JavaScript (ES5) 过渡到较新的 ES6 风格:

¥One final note. The JavaScript universe is currently in transition from old-school JavaScript (ES5) to the newer ES6 flavor:

// ES5
var x = 5;
setTimeout(function() { alert(x); }, 1000);
// ES6
const x = 5;
setTimeout(() => alert(x), 1000);

ES6 在更清晰的语法、更好的变量作用域、原生类支持等方面带来了许多主要优势。到目前为止,所有主流浏览器都支持它。鉴于此,我们在这些指南中的示例将使用 ES6。这并不意味着你不能将 PixiJS 与 ES5 程序一起使用!只需在心里用 "var" 替换 "let/const",扩展更短的函数传递语法,一切都会运行得很好。

¥ES6 brings a number of major advantages in terms of clearer syntax, better variable scoping, native class support, etc. By now, all major browsers support it. Given this, our examples in these guides will use ES6. This doesn't mean you can't use PixiJS with ES5 programs! Just mentally substitute "var" for "let/const", expand the shorter function-passing syntax, and everything will run just fine.

PixiJS 应用的组件

¥Components of a PixiJS Application

好的!完成这些注释后,让我们开始吧。编写 PixiJS 应用只需要几个步骤:

¥OK! With those notes out of the way, let's get started. There are only a few steps required to write a PixiJS application:

  • 创建 HTML 文件

    ¥Create an HTML file

  • 使用 Web 服务器提供文件

    ¥Serve the file with a web server

  • 加载 PixiJS 库

    ¥Load the PixiJS library

  • 创建一个 应用

    ¥Create an Application

  • 将生成的视图添加到 DOM

    ¥Add the generated view to the DOM

  • 将图片添加到舞台

    ¥Add an image to the stage

  • 编写更新循环

    ¥Write an update loop

让我们一起来了解一下它们。

¥Let's walk through them together.

HTML 文件

¥The HTML File

PixiJS 是一个在网页中运行的 JavaScript 库。所以我们首先需要的是文件中的一些 HTML。在真正的 PixiJS 应用中,你可能希望将显示嵌入到复杂的现有页面中,或者你可能希望显示区域填充整个页面。对于此演示,我们将构建一个空页面来开始:

¥PixiJS is a JavaScript library that runs in a web page. So the first thing we're going to need is some HTML in a file. In a real PixiJS application, you might want to embed your display within a complex existing page, or you might want your display area to fill the whole page. For this demo, we'll build an empty page to start:

<!doctype html>
<html>
<head>
</head>
<body>
<h1>Hello PixiJS</h1>
</body>
</html>

创建一个名为 pixi-test 的新文件夹,然后将此 HTML 复制并粘贴到 pixi-test 文件夹中名为 index.html 的新文件中。

¥Create a new folder named pixi-test, then copy and paste this HTML into a new file in the pixi-test folder named index.html.

提供文件服务

¥Serving the File

你需要运行一个 Web 服务器才能使用 PixiJS 进行本地开发。Web 浏览器阻止在本地加载的网页上加载本地文件(例如图片和音频文件)。如果你只是双击新的 HTML 文件,当你尝试将精灵添加到 PixiJS 舞台时,你会收到错误消息。

¥You will need to run a web server to develop locally with PixiJS. Web browsers prevent loading local files (such as images and audio files) on locally loaded web pages. If you just double-click your new HTML file, you'll get an error when you try to add a sprite to the PixiJS stage.

运行 Web 服务器听起来复杂且困难,但事实证明有许多简单的 Web 服务器可以满足此目的。在本指南中,我们将使用 Mongoose,但你也可以轻松使用 XAMPPhttp-server Node.js 包 来提供文件服务。

¥Running a web server sounds complex and difficult, but it turns out there are a number of simple web servers that will serve this purpose. For this guide, we're going to be working with Mongoose, but you could just as easily use XAMPP or the http-server Node.js package to serve your files.

要开始使用 Mongoose 为你的页面提供服务,请转到 Mongoose 下载页面 并下载适合你的操作系统的免费服务器。Mongoose 默认在其运行的文件夹中提供文件,因此将下载的可执行文件复制到你在上一步 (pixi-test) 中创建的文件夹中。双击可执行文件,告诉操作系统你信任该文件运行,然后你将拥有一个正在运行的 Web 服务器,为你的新文件夹提供服务。

¥To start serving your page with Mongoose, go to the Mongoose download page and download the free server for your operating system. Mongoose defaults to serving the files in the folder it's run in, so copy the downloaded executable into the folder you created in the prior step (pixi-test). Double-click the executable, tell your operating system that you trust the file to run, and you'll have a running web server, serving your new folder.

打开你选择的浏览器并在地址栏中输入 http://127.0.0.1:8080 来测试一切是否正常。(Mongoose 默认在端口 8080 上提供文件服务。)你应该看到 "你好 PixiJS",仅此而已。如果你在此步骤中收到错误,则意味着你没有将文件命名为 index.html 或者你错误配置了 Web 服务器。

¥Test that everything is working by opening your browser of choice and entering http://127.0.0.1:8080 in the location bar. (Mongoose by default serves files on port 8080.) You should see "Hello PixiJS" and nothing else. If you get an error at this step, it means you didn't name your file index.html or you mis-configured your web server.

加载 PixiJS

¥Loading PixiJS

好的,我们有了一个网页,并且正在为其提供服务。但它是空的。下一步是实际加载 PixiJS 库。如果我们正在构建一个真正的应用,我们希望从 Pixi Github 存储库 下载 PixiJS 的目标版本,这样我们的版本就不会改变。但对于这个示例应用,我们将仅使用 PixiJS 的 CDN 版本。将此行添加到 index.html 文件的 <head> 部分:

¥OK, so we have a web page, and we're serving it. But it's empty. The next step is to actually load the PixiJS library. If we were building a real application, we'd want to download a target version of PixiJS from the Pixi Github repo so that our version wouldn't change on us. But for this sample application, we'll just use the CDN version of PixiJS. Add this line to the <head> section of your index.html file:

<script src="https://pixijs.download/release/pixi.js"></script>

当你的页面加载时,这将包括 PixiJS 最新版本的非缩小版本,可供使用。我们使用非缩小版本,因为我们正在开发中。在生产中,你需要使用 pixi.min.js,它经过压缩以加快下载速度,并且排除了在构建项目时可以提供帮助的断言和弃用警告,但下载和运行需要更长的时间。

¥This will include a non-minified version of the latest version of PixiJS when your page loads, ready to be used. We use the non-minified version because we're in development. In production, you'd want to use pixi.min.js instead, which is compressed for faster download and excludes assertions and deprecation warnings that can help when building your project, but take longer to download and run.

创建应用

¥Creating an Application

如果我们不使用它,加载库并没有多大用处,所以下一步是启动 PixiJS。首先将 <h1>Hello PixiJS</h1> 行替换为脚本标记,如下所示:

¥Loading the library doesn't do much good if we don't use it, so the next step is to start up PixiJS. Start by replacing the line <h1>Hello PixiJS</h1> with a script tag like so:

<script type="module">
const app = new PIXI.Application();
await app.init({ width: 640, height: 360 });
</script>

我们在这里所做的是添加一个 JavaScript 代码块,并在该代码块中创建一个新的 PIXI.Application 实例。应用 是一个辅助程序类,可简化 PixiJS 的使用。它创建渲染器、创建舞台并启动更新代码。在生产中,你几乎肯定会想要自己执行这些步骤以增加自定义和控制 - 我们将在后面的指南中介绍如何执行此操作。目前,Application 类是开始使用 PixiJS 的完美方式,无需担心细节。Application 类还有一个方法 init,它将使用给定的选项初始化应用。此方法是异步的,因此我们使用 await 关键字在 Promise 完成后启动我们的逻辑。这是因为 PixiJS 在底层使用 WebGPU 或 WebGL,而前者的 API 是异步的。

¥What we're doing here is adding a JavaScript code block, and in that block creating a new PIXI.Application instance. Application is a helper class that simplifies working with PixiJS. It creates the renderer, creates the stage, and starts a ticker for updating. In production, you'll almost certainly want to do these steps yourself for added customization and control - we'll cover doing so in a later guide. For now, the Application class is a perfect way to start playing with PixiJS without worrying about the details. The Application class also has a method init that will initialize the application with the given options. This method is asynchronous, so we use the await keyword to start our logic after the promise has completed. This is because PixiJS uses WebGPU or WebGL under the hood, and the former API asynchronous.

将画布添加到 DOM

¥Adding the Canvas to the DOM

当 PIXI.Application 类创建渲染器时,它会构建一个将渲染到的 Canvas 元素。为了看到我们用 PixiJS 绘制的内容,我们需要将此 Canvas 元素添加到网页的 DOM 中。将以下行附加到页面的脚本块:

¥When the PIXI.Application class creates the renderer, it builds a Canvas element that it will render to. In order to see what we draw with PixiJS, we need to add this Canvas element to the web page's DOM. Append the following line to your page's script block:

  document.body.appendChild(app.canvas);

这将获取应用创建的画布(Canvas 元素)并将其添加到页面的主体中。

¥This takes the canvas created by the application (the Canvas element) and adds it to the body of your page.

创建精灵

¥Creating a Sprite

到目前为止,我们所做的只是准备工作。我们实际上并没有告诉 PixiJS 绘制任何东西。让我们通过添加要显示的图片来解决这个问题。

¥So far all we've been doing is prep work. We haven't actually told PixiJS to draw anything. Let's fix that by adding an image to be displayed.

在 PixiJS 中绘制图片的方法有很多种,但最简单的是使用 精灵。我们将在后面的指南中详细介绍场景图的工作原理,但现在你需要知道的是 PixiJS 渲染 容器 的层次结构。Sprite 是一种容器,它封装加载的图片资源以允许对其进行绘制、缩放、旋转等。

¥There are a number of ways to draw images in PixiJS, but the simplest is by using a Sprite. We'll get into the details of how the scene graph works in a later guide, but for now all you need to know is that PixiJS renders a hierarchy of Containers. A Sprite is a type of Container that wraps a loaded image resource to allow drawing it, scaling it, rotating it, and so forth.

在 PixiJS 渲染图片之前,需要先加载图片。就像在任何网页中一样,图片加载是异步发生的。我们将在后面的指南中详细讨论资源加载。现在,我们可以使用 PIXI.Sprite 类上的辅助方法来处理图片加载:

¥Before PixiJS can render an image, it needs to be loaded. Just like in any web page, image loading happens asynchronously. We'll talk a lot more about resource loading in later guides. For now, we can use a helper method on the PIXI.Sprite class to handle the image loading for us:

  // load the PNG asynchronously
await PIXI.Assets.load('sample.png');
let sprite = PIXI.Sprite.from('sample.png');

在此下载示例 PNG,并将其保存到 index.html 旁边的 pixi-test 目录中。

¥Download the sample PNG here, and save it into your pixi-test directory next to your index.html.

将精灵添加到舞台

¥Adding the Sprite to the Stage

最后,我们需要将新的精灵添加到舞台上。舞台只是一个 容器,它是场景图的根。舞台容器的每个子级都将在每一帧进行渲染。通过将精灵添加到舞台,我们告诉 PixiJS 的渲染器我们想要绘制它。

¥Finally, we need to add our new sprite to the stage. The stage is simply a Container that is the root of the scene graph. Every child of the stage container will be rendered every frame. By adding our sprite to the stage, we tell PixiJS's renderer we want to draw it.

  app.stage.addChild(sprite);

编写更新循环

¥Writing an Update Loop

虽然你可以将 PixiJS 用于静态内容,但对于大多数项目,你需要添加动画。我们的示例应用实际上正在加速,每秒在同一位置多次渲染同一精灵。要使图片移动,我们所要做的就是每帧更新一次其属性。为此,我们需要挂接到应用的代码中。股票代码是一个 PixiJS 对象,它每帧运行一个或多个回调。这样做非常容易。将以下内容添加到脚本块的末尾:

¥While you can use PixiJS for static content, for most projects you'll want to add animation. Our sample app is actually cranking away, rendering the same sprite in the same place multiple times a second. All we have to do to make the image move is to update its attributes once per frame. To do this, we want to hook into the application's ticker. A ticker is a PixiJS object that runs one or more callbacks each frame. Doing so is surprisingly easy. Add the following to the end of your script block:

  // Add a variable to count up the seconds our demo has been running
let elapsed = 0.0;
// Tell our application's ticker to run a new callback every frame, passing
// in the amount of time that has passed since the last tick
app.ticker.add((ticker) => {
// Add the time to our total elapsed time
elapsed += ticker.deltaTime;
// Update the sprite's X position based on the cosine of our elapsed time. We divide
// by 50 to slow the animation down a bit...
sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0;
});

你需要做的就是调用 app.ticker.add(...),向其传递一个回调函数,然后在该函数中更新你的场景。每一帧都会调用它,你可以移动、旋转等任何你想要驱动项目动画的方式。

¥All you need to do is to call app.ticker.add(...), pass it a callback function, and then update your scene in that function. It will get called every frame, and you can move, rotate etc. whatever you'd like to drive your project's animations.

把它们放在一起

¥Putting It All Together

就是这样!最简单的 PixiJS 项目!

¥That's it! The simplest PixiJS project!

这是所有事情都集中在一处的地方。如果出现错误,请检查你的文件并确保其匹配。

¥Here's the whole thing in one place. Check your file and make sure it matches if you're getting errors.

<!doctype html>
<html>
<head>
<script src="https://pixijs.download/release/pixi.min.js"></script>
</head>
<body>
<script type="module">
// Create the application helper and add its render target to the page
const app = new PIXI.Application();
await app.init({ width: 640, height: 360 })
document.body.appendChild(app.canvas);

// Create the sprite and add it to the stage
await PIXI.Assets.load('sample.png');
let sprite = PIXI.Sprite.from('sample.png');
app.stage.addChild(sprite);

// Add a ticker callback to move the sprite back and forth
let elapsed = 0.0;
app.ticker.add((ticker) => {
elapsed += ticker.deltaTime;
sprite.x = 100.0 + Math.cos(elapsed/50.0) * 100.0;
});
</script>
</body>
</html>

一旦一切顺利,接下来要做的就是阅读基础指南的其余部分,以更深入地了解这一切是如何工作的。

¥Once you have things working, the next thing to do is to read through the rest of the Basics guides to dig into how all this works in much greater depth.