W3docs

How to Add a Text on the HTML5 <canvas> Element

In this tutorial, you’ll find out how to add text on the HTML5 <canvas> element. For that, you need Javascript. Use the fillText() and strokeText() methods.

Solution with Javascript

To add a text to the HTML <canvas> element, you need to use the <kbd class="highlighted">fillText()</kbd> or <kbd class="highlighted">strokeText()</kbd> methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.

In the example below, we give a unique <span class="attribute">id</span> attribute to the <canvas> element, which allows us to access the element easily with Javascript. We also set the width and height of the element.

Example of adding a text on the <canvas> element with the fillText() method:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #canvas {
        background: #59b8de;
        width: 250px;
        height: 150px;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script>
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext("2d");
      context.fillStyle = "white";
      context.font = "bold 18px Arial";
      context.textAlign = "center";
      context.textBaseline = "middle";
      context.fillText("Text", canvas.width / 2, canvas.height / 2);
    </script>
  </body>
</html>

So, we accessed the <canvas> element by using the <kbd class="highlighted">getElementById</kbd> method, and then retrieved the 2D context. Then, we set text color with the fillStyle property, specified the font and added our text on the <canvas> by using the <kbd class="highlighted">fillText</kbd> method.

Now, let’s try an example with the <kbd class="highlighted">strokeText()</kbd> method.

Example of adding a text on the <canvas> element with the strokeText() method:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #canvas {
        background: #59b8de;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="250" height="100"></canvas>
    <script>
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext("2d");
      context.font = "30px Arial";
      context.strokeText("Text", 50, 50);
    </script>
  </body>
</html>