Text style and settings in HTML5 canvas

Text Alignment

We can set the text alignment of the text by setting the context’s textAlign property. The valid values will be left, right, and center.

ctx.textAlign = "center";

Text Baseline

We can change the text baseline by setting the context’s textBaseline property. The valid values will be top, hanging, middle, alphabetic, ideographic and bottom.

ctx.textBaseline = "middle";

Change the color of the text

canvas use the current fill and stroke style for the text. We can set the fillStyle or strokeStyle to change the fore color of the text.
ctx.fillStyle = "blue";

Change the font of the text

we use the font property of the canvas context to set the font of the drawn text that will contains the font style, size, and family name.

ctx.font = "24pt Verdana";
Draw text on canvas html5


The following example will draw the string ‘Welcome’ on the canvas.

  <title>Draw text</title>
    <style type="text/css">
        #MyCanvas {border:1px solid black;}
  <script type="text/javascript">
      function drawText() {
          var ctx;
          var canvas = document.getElementById("MyCanvas");
          if (canvas.getContext) {
              ctx = canvas.getContext("2d");
              ctx.fillStyle = "Red";
              ctx.textAlign = "center";
              ctx.textBaseline = "middle";
              ctx.font = "20pt verdana";
              ctx.fillText("Welcome", 100, 100);
<body onload="drawText();">
  <canvas id="MyCanvas" width="350" height="200">
  This browser or document mode doesn't support canvas object</canvas>