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;
In this example we use the
font
property to specify a custom font weight, size, and family.
<canvas id="canvas"></canvas>
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.
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. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
ctx.mozTextStyle
is implemented besides this property. Use
ctx.font
代替。
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
).
CanvasRenderingContext2D
CanvasRenderingContext2D
addHitRegion()
arc()
arcTo()
beginPath()
bezierCurveTo()
clearHitRegions()
clearRect()
clip()
closePath()
createImageData()
createLinearGradient()
createPattern()
createRadialGradient()
drawFocusIfNeeded()
drawImage()
drawWidgetAsOnScreen()
drawWindow()
ellipse()
fill()
fillRect()
fillText()
getImageData()
getLineDash()
getTransform()
isPointInPath()
isPointInStroke()
lineTo()
measureText()
moveTo()
putImageData()
quadraticCurveTo()
rect()
removeHitRegion()
resetTransform()
restore()
rotate()
save()
scale()
scrollPathIntoView()
setLineDash()
setTransform()
stroke()
strokeRect()
strokeText()
transform()
translate()