canvasでサーバー等に設置したフォントを使う

こちらではGoogleFontsを使いましたが、今回はディレクトリに設置したダウンロードフォントをcanvasで使うためのメモ。

//読ませるFonts
const fontFamilyList = [
  {
    name: "Noto Serif JP",
    url: "/assets/fonts/Noto_Serif_JP/NotoSerifJP-Regular.woff2",
    weight: "400",
  },
  {
    name: "Roboto",
    url: "/assets/fonts/Roboto/Roboto-Medium.woff2",
    weight: "500",
  }
]

/**
 * フォントファミリーの読み込み
 * @returns
 */
export const fetchFonts = async () => {

  const fontsLoad = async () => {

    for (let item of fontFamilyList) {
	  // forの中でawaitすることで、for内部の処理が全て終わったら"done"を返せる。
      await new Promise((resolve, reject) => {
        const font = new FontFace(item.name, `url(${item.url})`, {
          style: 'normal',
          weight: item.weight
        });

        font.load().then((res) => {
          // フォントがロードされたらフォントを適用する
          const documentFonts = document.fonts as any;
          documentFonts.add(font);
          resolve(res);
        }).catch((err) => {
          reject(err);
        });

      })
    }

    return "done"
  }

  const done = await fontsLoad();
  if (done) {
    return done
  }
}

呼び出し

const asyncFunc = async () => {
      const fatchDone = await fetchFonts();
      if (fatchDone) {
        //canvasの処理
      }
    }
    asyncFunc()

関連