HTML Canvas - fillText() Method



The HTML Canvas fillText() method can be used to draw a text string on the Canvas element at the specified co-ordinates with the current fillStyle property.

It is available in the CanvasRenderingContext2D interface and fills the text drawn by the context object.

Syntax

Following is the syntax of HTML Canvas fillText() method −

CanvasRenderingContext2D.fillText(text, x, y, text_width)

Parameters

Following is the list of parameters of this methods −

S.No Parameter & Description
1 text

The text string to be rendered onto the Canvas element.

2 x

x co-ordinate of the point from which text is to be drawn in the Canvas element.

3 y

y co-ordinate of the point from which text is to be drawn in the Canvas element.

4 text_width

Width of the text to be drawn in pixels.

Return values

It renders the string passed as a parameter on the Canvas element.

Example 1

The following example draws a string onto the Canvas element using HTML Canvas fillText() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "40px Verdana";
      context.fillText('TutorialsPoint', 20, 50);
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas FillText Method

Example 2

The following code adds a sentence string to the Canvas element using fillText() method and without font property.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="370" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "10px Verdana";
      context.fillText('This text is written on the canvas element using fillText() method', 20, 50);
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas FillText Method
html_canvas_text.htm
Advertisements