Phaser 3でカスタムフォントを使用する

フォントファイルを「assets」フォルダへ追加

今回はdist/assets/fontsというフォルダを作成して、そこにフォントファイルを配置しました。

GoogleFontsの「Dela Gothic One」というフォントをダウンロードして使用しています。

ダウンロードしたファイルは「ttf」形式だったので、以下のオンラインコンバーターでWebフォント向けの「woff2」へ変換して使用しています。

TTF to WOFF2 Converter

フォントを読み込む

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="preload" href="./assets/fonts/DelaGothicOne-Regular.woff2" as="font" type="font/woff2" crossorigin>
    <style>
      @font-face {
          font-family: DelaGothicOne-Regular;
          src: url('./assets/fonts/DelaGothicOne-Regular.woff2');
      }
  </style>
  </head>
  <body>
    <div id="game"></div>
    <script src="game.js"></script>
  </body>
</html>

HTMLにpreloadで優先的にフォントファイルを読み込ませます。

<link rel="preload" href="./assets/fonts/DelaGothicOne-Regular.woff2" as="font" type="font/woff2" crossorigin>

CSSの@font-faceでWebフォントを定義します。

@font-face {
   font-family: DelaGothicOne-Regular;
   src: url('./assets/fonts/DelaGothicOne-Regular.woff2');
}

読み込んだフォントを使用する

fontFamilyに定義したフォントファミリー名を指定すれば適用されます。

scene.add.text(0, 0, "こんにちは", { color: '#ffffff', fontSize: '28px' ,fontFamily: 'DelaGothicOne-Regular'});

コメント

タイトルとURLをコピーしました