我应该如何在 html 画布中使用粗体、斜体等字体文件?

Zha*_* Yi 1 html css fonts canvas

我从谷歌字体下载了一些字体,还有一些字体文件bold, italic, light, thin等。让我们Robot举个例子,这是我下载的两个字体文件:Roboto-Bold.ttf, Roboto-Regular.ttf.

我想知道我应该如何使用该文件Bold?如果我使用以下代码选择常规字体文件有什么区别:

canvasContext.font = `bold 20px Robot`
Run Code Online (Sandbox Code Playgroud)

上面的代码定义boldRobot字体系列。在这种情况下,我需要导入Roboto-Bold.ttf文件bold吗?对于同样的问题italiclightthin等。

Bhu*_*wan 5

您需要使用@font-face所有权重在 css 中定义字体。font-name为所有样式定义相同,只需用font-weight下面的方式区分它们

@font-face {
  font-family: "Roboto";
  src: url("Roboto-Regular.ttf");
  font-weight: normal;
}

@font-face {
  font-family: "Roboto";
  src: url("Roboto-Bold.ttf");
  font-weight: bold;
}

@font-face {
  font-family: "Roboto";
  src: url("Roboto-light.ttf");
  font-weight: 300;
}

@font-face {
  font-family: "Roboto";
  src: url("Roboto-thin.ttf");
  font-weight: 100;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的元素中使用它,比如

element {
  font-family: Roboto;
  font-weight:100; /* for Thin */
  font-weight:300; /* for Light */
  font-weight:normal; /* for Regular */
  font-weight:bold; /* for Bold */
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用 html<link>来嵌入您的字体,例如

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,400i,500" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)