Canvas Text

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

Properties and Methods

PropertyDescription
fontIt returns the current font settings and can be set to change the font.
textAlignIt 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.
textBaselineIt 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>

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *