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.
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.
A string parsed as CSS font
value. The default font is 10px sans-serif.
In this example we use the font
property to specify a custom font weight, size, and family.
html
<canvas id="canvas"></canvas>
js
const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "bold 48px serif"; ctx.strokeText("Hello world", 50, 100);
With the help of the FontFace
API, you can explicitly load fonts before using them in a canvas.
js
let f = new FontFace("test", "url(x)"); f.load().then(() => { // Ready to use the font in a canvas context });
Specification |
---|
HTML Standard # dom-context-2d-font-dev |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
font |
2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
CanvasRenderingContext2D
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font