Skip to main content

文本


无论是高分还是图表标签,文本通常是在项目中传达信息的最佳方式。 令人惊讶的是,使用 WebGL 将文本绘制到屏幕上是一个非常复杂的过程 - 根本没有内置支持。 PixiJS 提供的价值之一就是隐藏这种复杂性,让你可以用几行代码绘制不同样式、字体和颜色的文本。 此外,这些文本位与精灵一样都是场景对象 - 你可以对文本进行着色、旋转、Alpha 混合,以及像任何其他图形对象一样对待它。

英:Whether it's a high score or a diagram label, text is often the best way to convey information in your projects. Surprisingly, drawing text to the screen with WebGL is a very complex process - there's no built in support for it at all. One of the values PixiJS provides is in hiding this complexity to allow you to draw text in diverse styles, fonts and colors with a few lines of code. In addition, these bits of text are just as much scene objects as sprites - you can tint text, rotate it, alpha-blend it, and otherwise treat it like any other graphical object.

让我们深入研究一下它是如何工作的。

英:Let's dig into how this works.

有两种文本

由于在 WebGL 中处理文本存在挑战,PixiJS 提供了两种截然不同的解决方案。 在本指南中,我们将详细介绍这两种方法,以帮助你根据项目需求做出正确的选择。 选择错误的文本类型可能会对项目的性能和外观产生很大的负面影响。

英:Because of the challenges of working with text in WebGL, PixiJS provides two very different solutions. In this guide, we're going to go over both methods in some detail to help you make the right choice for your project's needs. Selecting the wrong text type can have a large negative impact on your project's performance and appearance.

文本对象

为了将文本绘制到屏幕上,你使用 文本 对象。 在幕后,此类使用浏览器的正常文本渲染将文本绘制到离屏缓冲区,然后使用该离屏缓冲区作为绘制文本对象的源。 实际上,这意味着每当你创建或更改文本时,PixiJS 都会创建该文本的新光栅化图片,然后将其视为精灵。 这种方法允许真正的富文本显示,同时保持较高的渲染速度。

英:In order to draw text to the screen, you use a Text object. Under the hood, this class draws text to an off-screen buffer using the browser's normal text rendering, then uses that offscreen buffer as the source for drawing the text object. Effectively what this means is that whenever you create or change text, PixiJS creates a new rasterized image of that text, and then treats it like a sprite. This approach allows truly rich text display while keeping rendering speed high.

因此,在使用 PIXI.Text 对象时,有两组选项 - 标准显示对象选项(如位置、旋转等)在文本内部光栅化后起作用,以及在光栅化时使用的文本样式选项。 由于文本一旦渲染后基本上只是一个精灵,因此无需查看标准选项。 相反,让我们关注文本的样式。

英:So when working with PIXI.Text objects, there are two sets of options - standard display object options like position, rotation, etc that work after the text is rasterized internally, and text style options that are used while rasterizing. Because text once rendered is basically just a sprite, there's no need to review the standard options. Instead, let's focus on how text is styled.

看看 文本示例代码

英:Check out the text example code.

文本样式

有很多文本样式选项可用(参见 TextStyle),但它们分为 5 个主要组:

英:There are a lot of text style options available (see TextStyle), but they break down into 5 main groups:

字体fontFamily 选择要使用的网络字体,fontSize 指定要绘制的文本的大小,以及字体粗细、样式和变体的选项。

英:Font: fontFamily to select the webfont to use, fontSize to specify the size of the text to draw, along with options for font weight, style and variant.

外貌: 使用 fill 设置颜色或添加 stroke 轮廓,包括渐变填充选项。

英:Appearance: Set the color with fill or add a stroke outline, including options for gradient fills.

Drop-Shadows: 使用 dropShadow 设置投影,并使用许多相关选项来指定偏移、模糊、不透明度等。

英:Drop-Shadows: Set a drop-shadow with dropShadow, with a host of related options to specify offset, blur, opacity, etc.

布局: 启用 wordWrapwordWrapWidth,然后自定义 lineHeightalignletterSpacing

英:Layout: Enable with wordWrap and wordWrapWidth, and then customize the lineHeight and align or letterSpacing

实用工具: 如果需要,添加 paddingtrim 额外空间来处理时髦的字体系列。

英:Utilities: Add padding or trim extra space to deal with funky font families if needed.

以交互方式测试文本样式的功能,看看这个工具

英:To interactively test out feature of Text Style, check out this tool.

加载和使用字体

为了让 PixiJS 构建 PIXI.Text 对象,你需要确保浏览器加载了你想要使用的字体。 不幸的是,在撰写本文时,PIXI.Loader 系统不支持加载字体文件,因此你需要使用第 3 方字体加载器来确保预加载你想要使用的任何自定义 Web 字体。 在项目的 CSS 中添加 @font-face 声明是不够的,因为在加载自定义字体时,浏览器会很乐意使用后备字体渲染文本。

英:In order for PixiJS to build a PIXI.Text object, you'll need to make sure that the font you want to use is loaded by the browser. Unfortunately, at the time of writing, the PIXI.Loader system does not support loading font files, so you'll need to use a 3rd party font loader to ensure that any custom web fonts you want to use are pre-loaded. It's not enough to add an @font-face declaration in your project's CSS because browsers will happily render text using a fallback font while your custom font loads.

任何可以加载网络字体的 javascript 库都可以工作,你只需要一些可以延迟启动项目直到浏览器完全加载字体的东西。

英:Any javascript library that can load a web font will work, you just want something that will delay starting your project until the font has been fully loaded by the browser.

FontFaceObserver 就是这样一个库。 下面是一个简单的示例,展示了如何使用它来确保在应用启动之前加载 Web 字体 "短筹码堆"。 首先,我们需要在 CSS 中声明 font-face:

英:One such library is FontFaceObserver. Here's a simple example that shows how to use it to ensure the web font "Short Stack" is loaded before your app starts. First, we need a font-face declaration in CSS:

@font-face {
font-family: Short Stack;
src: url(short-stack.woff2) format('woff2'),
url(short-stack.woff) format('woff');
}

现在浏览器知道我们的字体是什么以及如何查找源文件,是时候使用库来加载它们了:

英:Now that the browser knows what our font is and how to find the source files, it's time to use the library to load them:

// Create the loader
let font = new FontFaceObserver('Short Stack', {});
// Start loading the font
font.load().then(() => {
// Successful load, start up your PixiJS app as usual
let app = new PIXI.Application({ width: 640, height: 360 });
document.body.appendChild(app.view);
// ... etc ...

}, () => {
// Failed load, log the error or display a message to the user
alert('Unable to load required font!');
});

注意事项和陷阱

虽然 PixiJS 确实使文本处理变得容易,但你需要注意一些事情。

英:While PixiJS does make working with text easy, there are a few things you need to watch out for.

首先,更改现有文本字符串需要重新生成该文本的内部渲染,这是一个缓慢的操作,如果每帧更改许多文本对象,可能会影响性能。 如果你的项目需要同时在屏幕上显示大量频繁更改的文本,请考虑使用 PIXI.BitmapText 对象(如下所述),该对象使用固定位图字体,文本更改时不需要重新生成。

英:First, changing an existing text string requires re-generating the internal render of that text, which is a slow operation that can impact performance if you change many text objects each frame. If your project requires lots of frequently changing text on the screen at once, consider using a PIXI.BitmapText object (explained below) which uses a fixed bitmap font that doesn't require re-generation when text changes.

其次,缩放文本时要小心。 将文本对象的比例设置为 > 1.0 将导致显示模糊/像素化,因为文本不会以看起来清晰所需的更高分辨率重新渲染 - 它仍然与生成时的分辨率相同。 为了解决这个问题,你可以以更高的初始尺寸和缩小的比例进行渲染。 这将使用更多内存,但会让你的文本始终看起来清晰明快。

英:Second, be careful when scaling text. Setting a text object's scale to > 1.0 will result in blurry/pixely display, because the text is not re-rendered at the higher resolution needed to look sharp - it's still the same resolution it was when generated. To deal with this, you can render at a higher initial size and down-scale, instead. This will use more memory, but will allow your text to always look clear and crisp.

BitmapText

除了向项目添加文本的标准 PIXI.Text 方法之外,PixiJS 还支持位图字体。 位图字体与 TrueType 或其他通用字体有很大不同,因为它们由单个图片组成,其中包含你要使用的每个字母的预渲染版本。 当使用位图字体绘制文本时,PixiJS 不需要将字体字形渲染到临时缓冲区中 - 它可以简单地从主字体图片中复制并删除字符串的每个字符。

英:In addition to the standard PIXI.Text approach to adding text to your project, PixiJS also supports bitmap fonts. Bitmap fonts are very different from TrueType or other general purpose fonts, in that they consist of a single image containing pre-rendered versions of every letter you want to use. When drawing text with a bitmap font, PixiJS doesn't need to render the font glyphs into a temporary buffer - it can simply copy and stamp out each character of a string from the master font image.

这种方法的主要优点是速度 - 频繁更改文本的成本要低得多,并且由于共享源纹理,渲染每个附加文本片段的速度要快得多。

英:The primary advantage of this approach is speed - changing text frequently is much cheaper and rendering each additional piece of text is much faster due to the shared source texture.

看看 位图文本示例代码

英:Check out the bitmap text example code.

BitmapFont

  • 第三方解决方案
  • BitmapFont.来自自动生成

选择正确的方法

PIXI.文本

  • 静态文本
  • 少量文本对象
  • 高保真文本渲染(例如字距调整)
  • 文本布局(行和字母间距)

PIXI.位图文本

  • 动态文本
  • 大量文本对象
  • 内存较低