The HTML5 <canvas> element allows you to draw text on the canvas using the CanvasRenderingContext2D’s text API. This includes setting font styles, aligning text, and applying colors or effects.
Text rendering is essential for creating graphs, charts, games, and dynamic visualizations.
In this tutorial, you’ll learn:
- How to draw basic text.
- Customizing text styles.
- Text alignment and baselines.
- Adding shadows to text.
- Practical examples using canvas text.
1. Drawing Basic Text
The Canvas API provides two methods for rendering text:
- fillText(text, x, y): Draws filled text.
- strokeText(text, x, y): Draws outlined text.
Example 1: Drawing Basic Text
<canvas id="myCanvas" width="500" height="200" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Filled text ctx.font = "24px Arial"; ctx.fillStyle = "blue"; ctx.fillText("Hello, Canvas!", 50, 50); // Outlined text ctx.font = "24px Arial"; ctx.strokeStyle = "red"; ctx.lineWidth = 2; ctx.strokeText("Outlined Text", 50, 100); </script>
2. Customizing Text Styles
You can customize text appearance using the following properties:
- font: Sets the font size and family (e.g., “30px Arial”).
- fillStyle: Sets the color of filled text.
- strokeStyle: Sets the color of outlined text.
- lineWidth: Sets the width of the outline.
Example 2: Applying Font Styles
ctx.font = "bold 30px Verdana"; ctx.fillStyle = "green"; ctx.fillText("Bold Verdana Text", 50, 150);
Explanation:
- The font property allows you to combine font weight, size, and family.
3. Text Alignment
You can align text horizontally and vertically using:
- textAlign:
- start: Default; aligns text to the start of the drawing point.
- end: Aligns text to the end of the drawing point.
- center: Centers the text.
- left and right: Aligns text to the left or right of the drawing point.
- textBaseline:
- alphabetic: Default; aligns text to the baseline.
- top, hanging, middle, ideographic, and bottom: Aligns text to different vertical positions.
Example 3: Text Alignment and Baseline
ctx.font = "20px Arial"; ctx.fillStyle = "black"; // Horizontal alignment ctx.textAlign = "center"; ctx.fillText("Centered Text", 250, 50); ctx.textAlign = "right"; ctx.fillText("Right-Aligned Text", 450, 100); // Vertical baseline ctx.textAlign = "start"; ctx.textBaseline = "top"; ctx.fillText("Top Baseline", 50, 150); ctx.textBaseline = "bottom"; ctx.fillText("Bottom Baseline", 50, 200);
4. Adding Shadows to Text
Shadows add depth and style to text using these properties:
- shadowColor: Sets the shadow color.
- shadowBlur: Sets the shadow’s blur radius.
- shadowOffsetX: Sets the horizontal shadow offset.
- shadowOffsetY: Sets the vertical shadow offset.
Example 4: Adding Shadows
ctx.font = "30px Georgia"; ctx.fillStyle = "purple"; ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; ctx.shadowBlur = 10; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.fillText("Text with Shadow", 50, 100);
5. Measuring Text Width
Use measureText() to get the width of text. This is useful for dynamic layouts or precise alignment.
Example 5: Measuring Text
const text = "Measure this text!"; ctx.font = "24px Arial"; const metrics = ctx.measureText(text); ctx.fillStyle = "black"; ctx.fillText(text, 50, 50); // Display text width ctx.font = "16px Arial"; ctx.fillText(`Text width: ${metrics.width}px`, 50, 100);
Explanation:
- measureText(text).width returns the width of the specified text.
6. Combining Text with Shapes
You can mix text and shapes to create visual elements like buttons, banners, or labels.
Example 6: Button with Text
// Draw button ctx.fillStyle = "lightblue"; ctx.fillRect(50, 50, 200, 50); ctx.strokeStyle = "blue"; ctx.lineWidth = 2; ctx.strokeRect(50, 50, 200, 50); // Add text to button ctx.font = "20px Arial"; ctx.fillStyle = "black"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("Click Me", 150, 75);
7. Advanced Styling with Gradients
You can use gradients to style text dynamically.
Example 7: Gradient Text
// Create gradient const gradient = ctx.createLinearGradient(0, 0, 300, 0); gradient.addColorStop(0, "red"); gradient.addColorStop(0.5, "yellow"); gradient.addColorStop(1, "blue"); // Apply gradient to text ctx.font = "40px Arial"; ctx.fillStyle = gradient; ctx.fillText("Gradient Text", 50, 100);
8. Practical Example: Text in a Chart
Example 8: Chart with Labels
// Draw axes ctx.beginPath(); ctx.moveTo(50, 150); ctx.lineTo(350, 150); ctx.lineTo(50, 50); ctx.strokeStyle = "black"; ctx.stroke(); // Add labels ctx.font = "16px Arial"; ctx.fillStyle = "black"; ctx.textAlign = "center"; ctx.fillText("X-Axis", 200, 170); ctx.textAlign = "right"; ctx.textBaseline = "middle"; ctx.fillText("Y-Axis", 40, 100); // Add data labels ctx.textAlign = "center"; ctx.textBaseline = "top"; ctx.fillText("10", 100, 140); ctx.fillText("20", 200, 140); ctx.fillText("30", 300, 140);
9. Best Practices for Canvas Text
- Use Gradients and Shadows Sparingly:
- Avoid overusing effects to maintain readability.
- Align Text Dynamically:
- Use measureText() for precise placement.
- Choose Readable Fonts:
- Use clear fonts for small text sizes.
- Optimize for Performance:
- Cache text measurements for repeated layouts.
10. Browser Support
HTML5 Canvas text methods are supported in all modern browsers:
Feature | Supported? |
---|---|
fillText | Yes |
strokeText | Yes |
textAlign | Yes |
textBaseline | Yes |
shadowColor | Yes |
measureText | Yes |
11. Conclusion
In this tutorial, you learned:
- How to add and style text on a canvas.
- How to align and measure text.
- How to combine text with shapes and effects like shadows and gradients.