We can style text rendered on the canvas
by setting the size, weight, style, and font face
in a CSS-compliant text string that is applied to the context.font
property.
font |
Yes | Yes | Yes | Yes | Yes |
context.font='italic small-caps bold 12px arial';
Values | Description |
---|---|
font-style | Set font style. Possible values:
|
font-variant | Set the font variant. Possible values:
|
font-weight | Set the font weight. Possible values:
|
font-size | Set the font size in pixels |
font-family | Set the font family |
caption | Use the font used to caption controls, like buttons. |
icon | Assign the font used to label icons |
menu | Assign the font used in menus |
message-box | Assign the font used in dialog |
small-caption | Assign the font used in labeling small controls |
status-bar | Assign the fonts used in window status bar |
The basic format looks like this:
[font style] [font weight] [font size] [font face]
An example might be:
context.font = "italic bold 24px serif";
or:
context.font = "normal lighter 50px cursive";
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!-- ww w . j a va 2 s . com-->
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d");
ctx.font = "50px Verdana";
ctx.fillText("java2s.com", 0, 100);
</script>
</body>
</html>
The code above is rendered as follows:
The following code assigns the font used on status bar to canvas.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!-- ww w . j a v a2 s. co m-->
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d");
ctx.font = "status-bar";
ctx.fillText("java2s.com", 0, 100);
</script>
</body>
</html>
The code above is rendered as follows:
The following code creates bold font.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!-- www . ja v a 2 s . c o m-->
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d");
ctx.font = "bold 24px sans-serif";
ctx.fillText("java2s.com", 0, 100);
</script>
</body>
</html>
The code above is rendered as follows: