使用JavaScript加载TrueType字体是否可能?

4
我在服务器上有一个文件夹,里面存放了一些字体(myserver.com/fonts)。我的JavaScript应用程序需要使用这些字体,但我不知道如何加载和使用它们。有谁知道如何加载TrueType字体?我知道可以使用Cufon字体来做到这一点,但我更喜欢使用TrueType字体。
注:我是JavaScript新手,非常感谢任何示例。

使用 css font-face 声明 - Esailija
3个回答

7
使用CSS font-face。
@font-face { font-family: Delicious; src: url('myserver.com/fonts/Delicious-Roman.ttf'); } 
@font-face { font-family: Delicious; font-weight: bold; src: url('myserver.com/fonts/Delicious-Bold.otf'); }

然后使用 font-family 调用它:

h3 { font-family: Delicious, sans-serif; }

您可以使用任何经过许可的TrueType(.ttf)或OpenType(.otf)字体。


谢谢!使用@font-face会自动加载字体吗?我只是想知道这是如何工作的。 - user1745713
是的,它会自动加载字体。 - Gurpreet Singh
另一个快速的问题,这可以从JavaScript中完成吗?将来我会通过JSON文件动态添加字体,从那里做起会更容易。谢谢! - user1745713
你可以这样做: document.body.style.fontFamily = '...'; 这将为一个元素添加预定义的字体,而不是向页面添加字体样式。 - Gurpreet Singh

0

https://opentype.js.org 可以帮助您使用 JavaScript 加载 TrueType 字体

一个示例:

opentype.load('fonts/Roboto-Black.ttf', function(err, font) {
if (err) {
    alert('Font could not be loaded: ' + err);
} else {
    // Now let's display it on a canvas with id "canvas"
    const ctx = document.getElementById('canvas').getContext('2d');

    // Construct a Path object containing the letter shapes of the given text.
    // The other parameters are x, y and fontSize.
    // Note that y is the position of the baseline.
    const path = font.getPath('Hello, World!', 0, 150, 72);

    // If you just want to draw the text you can also use 
    font.draw(ctx,text, x, y, fontSize).path.draw(ctx);
    }
});

更多示例可在以下链接中找到: https://github.com/opentypejs/opentype.js

0

您可以通过 FontFace() 方法使用 javaScript 加载字体。

基础版本:

async function loadFonts() {
  const font = new FontFace("font-family name", "url(fontfile.ttf)", {
    style: "normal",
    weight: "400",
    stretch: "condensed",
  });
  // wait for font to be loaded
  await font.load();
  // add font to document
  document.fonts.add(font);

  // callback: do something, render a font to canvas etc
  document.body.classList.add("fonts-loaded");
}

示例:加载后将文本绘制到画布上

loadFonts(fonts);

function drawText() {
  const canvas = document.querySelector("canvas");
  const context = canvas.getContext("2d");
  context.font = "48px Inter";
  context.fontWeight = 400;
  context.fontStyle = "normal";
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.fillText("Inter", 150, 50);

  context.font = "48px Anton";
  context.fontWeight = 400;
  context.fontStyle = "normal";
  context.textAlign = "left";
  context.textBaseline = "top";
  context.fillText("Anton", 0, 100);
  
  console.log("draw");
}


async function loadFonts(fontsToLoad) {
    for (let i = 0; i < fontsToLoad.length; i++) {
      let fontProps = fontsToLoad[i];
      let fontFamily = fontProps["font-family"];
      let fontWeight = fontProps["font-weight"];
      let fontStyle = fontProps["font-style"];
      let fontUrl = Array.isArray(fontProps["src"]) ?
        fontProps["src"][0][0] :
        fontProps["src"];
      if (fontUrl.indexOf("url(") === -1) {
        fontUrl = "url(" + fontUrl + ")";
      }
      let fontFormat = fontProps["src"][0][1] ? fontProps["src"][1] : "";
      const font = new FontFace(fontFamily, fontUrl);
      font.weight = fontWeight;
      font.style = fontStyle;
      await font.load();
      document.fonts.add(font);
      console.log(fontFamily, "loaded");
    }
    drawText()
}
canvas {
  height: 50vh;
  border: 1px solid red
}
<p>Draw to canvas</p>
<canvas class="text" />

<script>
  let fonts = [{
      // Inter as replacement
      "font-family": "Inter",
      "font-style": "normal",
      "font-weight": 400,
      src: "https://fonts.gstatic.com/s/inter/v12/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1ZL7.woff2"
    },
    {
      // Anton  as replacement
      "font-family": "Anton",
      "font-style": "normal",
      "font-weight": 400,
      src: "https://fonts.gstatic.com/s/anton/v23/1Ptgg87LROyAm3Kz-C8.woff2"
    }
  ];
</script>

以上的画布示例如果使用CSS加载字体,则可能无法正常工作。
大多数浏览器不会加载未在HTML中使用的字体
FontFace()方法确保所有字体都被加载-无论它们是否应用于可见元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接