JavaScript > Browser APIs > Canvas API > Drawing text
Drawing Text on a Canvas with JavaScript
Learn how to draw text on an HTML5 canvas using JavaScript, including styling the text with fonts, colors, and alignment. This tutorial provides a comprehensive guide with code examples.
Basic Text Drawing
This snippet demonstrates the most basic way to draw text on a canvas. First, we get a reference to the canvas element and its 2D rendering context. Then, we set the font property, specifying the size and font family. Finally, we use `fillText()` to draw the text 'Hello Canvas!' at position (50, 50) on the canvas. The x and y coordinates determine the top-left position of the text baseline.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
ctx.fillText('Hello Canvas!', 50, 50);
Styling Text with Font Properties
This example shows how to style text using different font properties and colors. `ctx.font` can take a string that specifies the font style (e.g., 'bold', 'italic'), font size, and font family. `ctx.fillStyle` sets the color of the text. Other styling options include `ctx.strokeStyle` to outline the text and `ctx.lineWidth` to set the outline thickness.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = 'bold 24px serif'; // Example: bold serif font
ctx.fillStyle = 'blue'; // Set text color
ctx.fillText('Styled Text', 50, 100);
Text Alignment
This snippet demonstrates how to align text both horizontally and vertically. `ctx.textAlign` can be set to 'left', 'right', 'center', 'start', or 'end'. `ctx.textBaseline` can be set to 'top', 'bottom', 'middle', 'alphabetic', 'hanging', or 'ideographic'. This allows for precise placement of text relative to a given point. In the example, the text is centered both horizontally and vertically on the canvas.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '20px sans-serif';
ctx.textAlign = 'center'; // Align text horizontally
ctx.textBaseline = 'middle'; // Align text vertically
ctx.fillText('Centered Text', canvas.width / 2, canvas.height / 2);
Concepts behind the snippet
The Canvas API provides a powerful way to draw graphics and text using JavaScript. It uses a raster (pixel-based) approach. The `getContext('2d')` method returns a drawing context that allows you to manipulate the canvas. The `fillText()` method is used to draw filled text, while `strokeText()` draws only the outline of the text. Understanding font properties, text alignment, and the canvas coordinate system is crucial for effective text rendering.
Real-Life Use Case Section
Drawing text on a canvas is useful in many scenarios: Creating dynamic charts and graphs, generating watermarks on images, building custom text editors, creating interactive games with text overlays, and developing visual art tools.
Best Practices
Interview Tip
Be prepared to discuss the differences between `fillText()` and `strokeText()`, as well as the various options for styling and aligning text on a canvas. Also, understand the performance implications of drawing text frequently, and how to optimize it using techniques like caching.
When to use them
Use the Canvas API for drawing text when you need fine-grained control over text rendering, dynamic text updates, or integration with other graphical elements. Avoid using it for large blocks of static text, as it's less performant than using standard HTML text elements.
Memory footprint
Drawing text on a canvas creates pixel data, which can consume memory, especially for large canvases or complex text styles. Regularly clear the canvas or optimize the drawing process to manage memory usage effectively.
Alternatives
Alternatives to using the Canvas API for text rendering include: SVG (Scalable Vector Graphics), which is suitable for resolution-independent graphics, and standard HTML text elements combined with CSS for basic text styling. WebGL can also be used for advanced 3D text rendering.
Pros
Cons
FAQ
-
How do I change the color of the text?
Use the `ctx.fillStyle` property to set the color of the text before calling `fillText()`. -
How do I make the text bold?
Include 'bold' in the `ctx.font` property string, for example: `ctx.font = 'bold 20px Arial';` -
How do I measure the width of the text before drawing it?
Use the `ctx.measureText()` method to get a `TextMetrics` object containing the width of the text.