You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Phaser 3字体族设置不生效及字体加载检测与设置方法咨询

Phaser 3 字体加载与应用问题解决方案

1. 检测字体加载完成的方法(无需外部库)

Phaser 3 本身没有内置字体加载检测事件,但可以结合浏览器原生 API 或 Phaser 的文本渲染机制实现:

方法一:使用浏览器 Font Loading API

直接利用浏览器的 document.fonts 对象监听字体加载状态,完成后再启动游戏或执行渲染逻辑:

// 检测所有字体加载完成
document.fonts.ready.then(() => {
  // 初始化Phaser游戏
  const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    scene: [MainScene]
  };
  new Phaser.Game(config);
});

// 单独检测指定字体
document.fonts.load('16px CustomFont').then(() => {
  console.log('CustomFont 加载完成');
  // 在这里执行依赖该字体的渲染操作
});

方法二:通过Phaser文本对象间接检测

创建隐藏的测试文本,通过监听文本宽度变化判断字体是否切换完成:

class PreloadScene extends Phaser.Scene {
  constructor() {
    super('PreloadScene');
    this.fontLoaded = false;
  }

  create() {
    // 创建测试文本,同时指定目标字体和备用字体
    const testText = this.add.text(0, -100, 'abcdefghijklmnopqrstuvwxyz', {
      fontFamily: 'CustomFont, sans-serif',
      fontSize: '24px'
    });
    testText.previousWidth = testText.width;

    // 定时检测宽度变化
    this.time.addEvent({
      delay: 100,
      callback: () => {
        if (!this.fontLoaded && testText.width !== testText.previousWidth) {
          this.fontLoaded = true;
          testText.destroy();
          // 字体加载完成,进入主场景
          this.scene.start('MainScene');
        }
        testText.previousWidth = testText.width;
      },
      loop: true,
      callbackScope: this
    });
  }
}

2. 在Phaser 3中设置并应用字体族

步骤1:预加载字体

通过 CSS @font-face 引入字体(可放在 HTML 的 <style> 标签或外部 CSS 文件中):

@font-face {
  font-family: 'CustomFont';
  src: url('assets/fonts/custom-font.woff2') format('woff2'),
       url('assets/fonts/custom-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

步骤2:在Phaser中应用字体

  • 单个文本对象:创建文本时在样式配置中指定 fontFamily:
const titleText = this.add.text(400, 300, '游戏标题', {
  fontFamily: 'CustomFont',
  fontSize: '48px',
  fill: '#fff',
  align: 'center'
}).setOrigin(0.5);
  • 全局默认字体:通过全局配置统一设置所有文本的默认字体:
// 全局设置文本默认样式
Phaser.GameObjects.Text.defaultStyle.fontFamily = 'CustomFont';

// 或在游戏配置中指定
const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: [PreloadScene, MainScene],
  text: {
    fontFamily: 'CustomFont'
  }
};

3. 无需外部库的纯实现方案

上述所有方法都不需要依赖第三方库,仅通过 Phaser 自身 API 结合浏览器原生能力即可完成:

  1. 用 CSS @font-face 预加载字体文件
  2. 用 Font Loading API 或 Phaser 文本对象检测加载状态
  3. 等待字体加载完成后,再渲染使用该字体的文本内容

内容的提问来源于stack exchange,提问作者맨들맨들

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 17:17:17