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.

句法

ctx.font = value;
					

选项

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

范例

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);
					

结果

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
});
					

规范

规范 状态 注释
HTML 实时标准
The definition of 'CanvasRenderingContext2D.font' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
font Chrome Yes Edge 12 Firefox 3.5 IE 9 Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

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 代替。
  • In Gecko, when setting a system font as the value of a canvas 2D context's font (如, 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 ).

另请参阅

元数据

  • 最后修改: