Canvas How to - Align Text








Question

We would like to know how to align Text.

Answer


<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas" width="578" height="200"></canvas>
  <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var x = canvas.width / 2;
      var y = canvas.height / 2;
      context.font = '30pt Calibri';
      context.textAlign = 'center';
      context.fillStyle = 'blue';
      context.fillText('Hello World!', x, y);
    </script>
</body><!--   w w  w.  j av a2  s .  c  o  m-->
</html>

The code above is rendered as follows: