CanvasRenderingContext2D: fontStretch 属性

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

Canvas APICanvasRenderingContext2D.fontStretch 属性用于指定在绘制文本时字体可以如何被拉伸或压缩。

该属性对应于 font-stretch CSS 属性,当使用关键字时(不支持百分比值)。

字体拉伸值(字符串)。可以是以下之一:ultra-condensedextra-condensedcondensedsemi-condensednormal(默认)、semi-expandedexpandedextra-expandedultra-expanded

该属性可用于获取或设置字体拉伸值。

示例

在此示例中,我们将使用 fontStretch 属性的每种受支持的值来显示文本“Hello World”。每个案例中还会通过读取属性来显示拉伸值。

HTML

html
<canvas id="canvas" width="700" height="310"></canvas>

JavaScript

首先,我们获取 HTML 文件中声明的 canvas,并用它来获取稍后用于绘制文本的 CanvasRenderingContext2D

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

示例中的下一步是加载一个可变字体,该字体可以在宽度轴上进行变化。这是必需的,因为 fontStretch 只能拉伸包含有关拉伸时字形如何绘制的信息的字体——否则文本将使用字体最接近的可用字体拉伸值绘制,通常是正常宽度。

在这种情况下,我们使用 FontFaceInconsolata Google 字体定义一个字体面,该字体支持从 50% 到 200% 的字体宽度(这使我们能够演示从 ultra-condensedultra-expandedfontStretch 值)。然后,我们将其添加到文档的 FontFaceSetdocument.fonts)中,以便可以用于绘制。

js
const fontFile = new FontFace(
  "Inconsolata",
  'url("https://fonts.gstatic.com/s/inconsolata/v31/QlddNThLqRwH-OJ1UHjlKENVzlm-WkL3GZQmAwPyya15.woff2") format("woff2")',
  { stretch: "50% 200%" },
);

document.fonts.add(fontFile);

下面的代码随后调用 FontFaceSet.load() 来获取并加载 Google 字体。请注意,此调用会设置所需字体的大小,并返回一个在字体加载完成后解析的 promise。

然后,我们将下载的字体面分配给上下文,并使用上下文在每个关键字拉伸级别上将文本绘制到 canvas 上。请注意,这里再次指定了所需字体的大小(这不必与加载的字体大小匹配)。

js
document.fonts.load("30px Inconsolata").then(
  () => {
    ctx.font = "30px 'Inconsolata'";
    // Default (normal)
    ctx.fillText(`Hello world (default: ${ctx.fontStretch})`, 5, 20);

    ctx.fontStretch = "ultra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 50);

    ctx.fontStretch = "extra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 80);

    ctx.fontStretch = "condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 110);

    ctx.fontStretch = "semi-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 140);

    ctx.fontStretch = "extra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 170);

    ctx.fontStretch = "semi-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 200);

    ctx.fontStretch = "expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 230);

    ctx.fontStretch = "extra-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 260);

    ctx.fontStretch = "ultra-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 290);
  },
  (err) => {
    console.error(err);
  },
);

结果

规范

规范
HTML
# dom-context-2d-fontstretch

浏览器兼容性