HTML5 Canvas Reference - font








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.

Browser compatibility

font Yes Yes Yes Yes Yes

JavaScript syntax

context.font='italic small-caps bold 12px arial';

Property Values

Values Description
font-style Set font style. Possible values:
  • normal
  • italic
  • oblique
font-variant Set the font variant. Possible values:
  • normal
  • small-caps
font-weight Set the font weight. Possible values:
  • normal
  • bold
  • bolder
  • lighter
  • 100
  • 200
  • 300
  • 400
  • 500
  • 600
  • 700
  • 800
  • 900
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";




Example


<!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:





Example 2

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:

Example 3

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: