CanvasRenderingContext2D:fontKerning 属性

可用性有限

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

CanvasRenderingContext2D.fontKerning 属性,属于 Canvas API,用于指定如何使用字体字偶间距信息。

字偶间距(Kerning)会调整比例字体中相邻字母的间距,允许它们在有可用空间时互相“侵入”彼此的视觉区域。例如,在字偶间距良好的字体中,字符 AVTaWe 会互相嵌套,使字符间距比没有字偶间距的等效文本更均匀、更悦目。

此属性对应于 font-kerning CSS 属性。

此属性可用于获取或设置其值。

允许的值为:

auto

浏览器确定是否应使用字偶间距。例如,某些浏览器会在小字体上禁用字偶间距,因为应用字偶间距可能会损害文本的可读性。

normal

必须应用字体中存储的字偶间距信息。

none

禁用字体中存储的字偶间距信息。

示例

在此示例中,我们使用 textRendering 属性的每个支持值来显示文本“AVA Ta We”。

HTML

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

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px serif";

// Default (auto)
ctx.fillText(`AVA Ta We (default: ${ctx.fontKerning})`, 5, 30);

// Font kerning: normal
ctx.fontKerning = "normal";
ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 70);

// Font kerning: none
ctx.fontKerning = "none";
ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 110);

结果

请注意,最后一个字符串禁用了字偶间距,因此相邻字符是均匀分布的。

规范

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

浏览器兼容性