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


The Canvas 2D API's CanvasRenderingContext2D method fillText() draws a text string at the given coordinates while filling the characters with the current fillStyle.

On the canvas, filled text is drawn using the fillText() method. The text is black by default.

Syntax

Following is the syntax to fill text in HTML5

context.fillText(text, x, y, maxWidth);

Where,

  • X − The point on the x-axis where the text should start to be drawn in pixels.

  • Y − The baseline's y-axis coordinate, in pixels, at which to start rendering the text.

  • text − This is a string containing the text string that should be rendered in the context.

  • maxwidth − The most pixels that the text can have at its widest point. There is no restriction on the text's width if it is not stated.

For getting the better understanding, lets dive into the following examples one by one.

Using filltext() Method

The canvas is filled with text drawn using the fillText() method. The text is always displayed in black.

Example

In the following example we are using filltext() to draw a text on our canvas of our required font.

<!DOCTYPE html> <html> <body> <canvas id="canvas" height="400" width="500"></canvas> <script> const canvas = document.getElementById('canvas'); if (canvas.getContext) { const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.font = '60px cursive'; ctx.fillText('Hello, World!', 100, 200); } </script> </body> </html>

On executing the above script ,the filltext() gets activated, which makes it draw the text "hello,world!" on our canvas using the font used in the script.

Adding Linear Gradient() Function

The backdrop image is set to a linear gradient using the linear-gradient() method. You need to define at least two colour stops in order to build a linear gradient.

Example

Considering the following example we are using filltext() along with the linear gradient to get our text drawn in colorfulway.

<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="150"></canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font = "30px Verdana";var gradient = ctx.createLinearGradient(0, 0, c.width, 0); gradient.addColorStop("0", "magenta"); gradient.addColorStop("0.5", "blue"); gradient.addColorStop("1.0", "red"); ctx.fillStyle = gradient; ctx.fillText("TUTORIALS POINT!", 10, 90); </script> </body> </html>

When the script gets executed, the linear gradients get triggered and make the text "tutorialspoint!" to be drawn on the canvas.

Updated on: 12-Oct-2022

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements