JavaScript Development Space

How to Draw a Text String Using the HTML Canvas Element

The HTML <canvas> element is a powerful tool for rendering 2D graphics, including text strings, directly within a web browser. By using JavaScript and the CanvasRenderingContext2D API, you can customize and draw text with precision.

Steps to Draw Text on a Canvas

  1. Add a <canvas> Element Include a <canvas> tag in your HTML with specified dimensions.
  2. Access the 2D Rendering Context Use the getContext('2d') method to interact with the canvas.
  3. Draw the Text Utilize methods like fillText() or strokeText() to render text on the canvas.

Example Code

html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Canvas Text Example</title>
7 </head>
8 <body>
9 <canvas id="textCanvas" width="400" height="200" style="border:1px solid black;"></canvas>
10
11 <script>
12 const canvas = document.getElementById('textCanvas');
13 const ctx = canvas.getContext('2d');
14
15 // Set font properties
16 ctx.font = '24px Arial';
17 ctx.fillStyle = 'blue';
18 ctx.textAlign = 'center';
19 ctx.textBaseline = 'middle';
20
21 // Draw filled text
22 ctx.fillText('Hello, Canvas!', canvas.width / 2, canvas.height / 2);
23
24 // Optional: Draw outlined text
25 ctx.strokeStyle = 'red';
26 ctx.strokeText('Outline Example', canvas.width / 2, canvas.height / 2 + 30);
27 </script>
28 </body>
29 </html>

Key Methods for Drawing Text

  1. fillText(text, x, y [, maxWidth])
  • Draws filled text at the specified coordinates.
  • Example: ctx.fillText('Hello', 50, 50);
  1. strokeText(text, x, y [, maxWidth])
  • Draws outlined text at the specified coordinates.
  • Example: ctx.strokeText('Outline', 50, 100);

Additional Customizations

1. Font Settings

  • Customize the font using the font property:

Example: ctx.font = 'italic bold 20px Verdana';

2. Text Alignment

  • Adjust alignment with textAlign(start, end, center, left, right).

3. Text Baseline

  • Set the baseline using textBaseline(top, middle, alphabetic, etc.).

4. Colors and Styles

  • Use fillStyle and strokeStyle for colors.

Conclusion

The HTML <canvas> element and its fillText() and strokeText() methods provide an effective way to render and style text strings. With customizable options like fonts, colors, and alignment, you can create stunning visuals tailored to your application's needs.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.