The CanvasRenderingContext2D
.font
property of the Canvas 2D API specifies the current text style being used when drawing text. This string uses the same syntax as the CSS font specifier. The default font is 10px sans-serif.
ctx.font = value;
font
propertyThis is just a simple code snippet using the font
property to set a different font size and font family.
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 50, 100);
Edit the code below and see your changes update live in the canvas:
With the help of the FontFace
API, you can explicitly load fonts before using it in canvas.
var f = new FontFace('test', 'url(x)'); f.load().then(function() { // Ready to use the font in a canvas context });
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.font' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | 3.5 | 9 | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
ctx.mozTextStyle
is implemented besides this property. Don't use it.font
(e.g. menu
), getting the font value fails to return the expected font (it returns nothing). This is fixed in Firefox's new parallel CSS engine (also known as Quantum CSS or Stylo, planned for release in Firefox 57) (bug 1374885).CanvasRenderingContext2D
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font