HTML5 canvas allows creating text using different font and text properties presented below:

Properties and Methods

Property Description
font It returns the current font settings and can be set to change the font.
textAlign It returns the current text alignment settings and can be set to change the alignment. The property has the following values: start, end, left, right, and center.
textBaseline It returns the current baseline alignment settings and can be set to change the baseline alignment. The property has the following values: top, hanging, middle, alphabetic, ideographic, and bottom.
fillText(text, x, y) It draws a filled text at the position indicated by the given coordinates x and y.
strokeText(text, x, y) It strokes the text at the position indicated by the given coordinates x and y.

Example of the fillText() property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <canvas id="exampleCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
      Your browser does not support the canvas element.
    </canvas>
    <script>
      var canvas = document.getElementById("exampleCanvas");
      var ctx = canvas.getContext("2d");
      ctx.font = "30px Arial";
      ctx.fillText("Hello World", 70, 80);
    </script>
  </body>
</html>

Example of the textStroke() property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <canvas id="exampleCanvas" width="250" height="150" style="border:1px solid #d3d3d3;">
      Your browser does not support the canvas element.
    </canvas>
    <script>
      var canvas = document.getElementById("exampleCanvas");
      var ctx = canvas.getContext("2d");
      ctx.font = "27px Arial";
      ctx.strokeText("Canvas text", 40, 70);
    </script>
  </body>
</html>

Example of adding color and centering text:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <canvas id="exampleCanvas" width="400" height="250" style="border:1px solid #d3d3d3;">
      Your browser does not support the canvas element.
    </canvas>
    <script>
      var canvas = document.getElementById("exampleCanvas");
      var ctx = canvas.getContext("2d");
      ctx.font = "40px Comic Sans MS";
      ctx.fillStyle = "red";
      ctx.textAlign = "center";
      ctx.fillText("Canvas Text", canvas.width / 2, canvas.height / 2);
    </script>
  </body>
</html>

Practice Your Knowledge

What is the functionality of the HTML5 canvas 'fillText()' method in relation to text?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?