CanvasRenderingContext2D.font - Web APIs 编辑

The CanvasRenderingContext2D.font property of the Canvas 2D API specifies the current text style to use when drawing text. This string uses the same syntax as the CSS font specifier.

Syntax

ctx.font = value;

Options

value
A DOMString parsed as CSS font value. The default font is 10px sans-serif.

Examples

Using a custom font

In this example we use the font property to specify a custom font weight, size, and family.

HTML

<canvas id="canvas"></canvas>

JavaScript

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

ctx.font = 'bold 48px serif';
ctx.strokeText('Hello world', 50, 100);

Result

Loading fonts with the CSS Font Loading API

With the help of the FontFace API, you can explicitly load fonts before using them in a canvas.

let f = new FontFace('test', 'url(x)');

f.load().then(function() {
  // Ready to use the font in a canvas context
});

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.font' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

Gecko-specific notes

  • In Gecko-based browsers, such as Firefox, a non-standard and deprecated property ctx.mozTextStyle is implemented besides this property. Use ctx.font instead.
  • In Gecko, when setting a system font as the value of a canvas 2D context's font (e.g., menu), getting the font value used to fail to return the expected font (it returns nothing). This is fixed in Firefox's Quantum/Stylo parallel CSS engine, released in Firefox 57 (bug 1374885).

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:127 次

字数:4292

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文