Skip to main content

Archive

Show more

Working with Text in Canvas

Working with Text in Canvas

Canvas in HTML provides the ability to draw text directly onto the canvas, allowing you to add textual content to your graphics and visualizations. Here's how to work with text in the canvas:


1. Setting Font Properties

Before drawing text, you can specify font properties such as font family, size, and style using the font property:

// Set font properties
ctx.font = 'italic 24px Arial';

This sets the font to italic, with a size of 24 pixels, and Arial as the font family.


2. Drawing Text

To draw text on the canvas, use the fillText() or strokeText() method:

// Fill text
ctx.fillText('Hello, Canvas!', 50, 50); // Text, x-coordinate, y-coordinate

// Stroke text
ctx.strokeStyle = 'red';
ctx.strokeText('Hello, Stroke!', 50, 100); // Text, x-coordinate, y-coordinate

The fillText() method fills the specified text with the current fill color, while strokeText() draws an outline of the text with the current stroke color.


3. Text Alignment and Baseline

You can specify text alignment and baseline using the textAlign and textBaseline properties:

// Set text alignment
ctx.textAlign = 'center'; // 'start', 'end', 'left', 'right', 'center'

// Set text baseline
ctx.textBaseline = 'middle'; // 'top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'

This aligns the text horizontally at the center and vertically at the middle.


Example:

Here's a simple example demonstrating how to work with text in the canvas:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Text Example</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200" style="border:1px solid black"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        
        // Set font properties
        ctx.font = 'italic 24px Arial';
        
        // Fill text
        ctx.fillText('Hello, Canvas!', 200, 100);
        
        // Set text alignment and baseline
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        // Stroke text
        ctx.strokeStyle = 'red';
        ctx.strokeText('Aligned Text', 200, 150);
    </script>
</body>
</html>

Conclusion

Working with text in the canvas allows you to add textual content to your canvas drawings, enhancing their visual appeal and providing context to your graphics. By setting font properties, drawing text, and adjusting alignment and baseline, you can create dynamic and informative canvas-based applications.

Comments