Computer >> Computer tutorials >  >> Programming >> HTML

How to draw a text with fillText() in HTML5?


To draw a filled text on the canvas in HTML5, use the fillText() method. Here’s the syntax of the fillText() method. It fills the given text at the given position indicated by the given coordinates x and y. The default color is black.

fillText(text, x, y [, maxWidth ] )

Here are the parameter values of the fillText() method:

S. No
Parameter
Description
1
text
The text to be written
2
x
x coordinate
3
y
y coordinate
4
maxWidth
Maximum allowed width, in pixels

How to draw a text with fillText() in HTML5?

Example

You can try to run the following code to draw a text with fillText() in HTML5:

<!DOCTYPE html>
<html>
   <head>
      <title>HTML5 Canvas fillText()</title>
   </head>
   <body>
      <canvas id="newCanvas" width="400" height="150" style="border:1px solid #000000;"></canvas>
      <script>
         var c = document.getElementById("newCanvas");
         var ctxt = c.getContext("2d");
         ctxt.fillStyle = '#00F';
         ctxt.font = "20px Georgia";
         ctxt.fillText("Tutorialspoint", 10, 50);
         ctxt.fillStyle = '#Cff765';
         ctxt.font = "30px Verdana";
         ctxt.fillText("Simply Easy Learning!", 10, 90);
      </script>
   </body>
</html>