YouTip LogoYouTip

Canvas Measuretext

## HTML Canvas `measureText()` Method The `measureText()` method in the HTML Canvas 2D Context API allows you to measure the dimensions of a specified string of text before rendering it to the canvas. It returns a `TextMetrics` object containing geometric information (such as width) based on the current canvas font settings. --- ## Definition and Usage When rendering dynamic text onto a canvas, you often need to know how much space the text will occupy. This is crucial for tasks such as: * Aligning text (left, right, center). * Wrapping long text into multiple lines. * Creating responsive text boxes, buttons, or speech bubbles that scale with their content. The `measureText()` method calculates these dimensions using the current font style defined by `context.font`. ### Syntax ```javascript const metrics = context.measureText(text); const width = metrics.width; ``` ### Parameter Values | Parameter | Type | Description | | :--- | :--- | :--- | | `text` | *String* | The text string to be measured. | ### Return Value Returns a **`TextMetrics`** object. * In its most basic and widely supported form, this object contains a `width` property (a double-precision float representing the width of the text in CSS pixels). * Modern browsers also support advanced properties on this object, such as `actualBoundingBoxLeft`, `actualBoundingBoxRight`, `fontBoundingBoxAscent`, and `fontBoundingBoxDescent` for precise vertical and horizontal alignment. --- ## Code Examples ### Example 1: Basic Text Width Measurement This example demonstrates how to measure the width of a text string and display both the measurement and the text itself on the canvas. ```html Your browser does not support the HTML5 canvas tag. ``` ### Example 2: Dynamic Text Centering You can use `measureText()` to manually center text on a canvas by calculating the starting X-coordinate: ```javascript const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.font = "24px Georgia"; const message = "Centered Text"; // Calculate coordinates const textWidth = ctx.measureText(message).width; const xPosition = (canvas.width - textWidth) / 2; const yPosition = canvas.height / 2; // Draw the text ctx.fillText(message, xPosition, yPosition); ``` --- ## Important Considerations 1. **Set the Font First:** Always set your canvas font style (`ctx.font = "..."`) *before* calling `measureText()`. If you measure the text first, the canvas will use its default fallback font (usually `10px sans-serif`), resulting in incorrect measurements. 2. **CSS vs. Canvas Dimensions:** Ensure that the canvas width and height are set via HTML attributes (`width` and `height`) rather than CSS styles to prevent scaling distortion during measurements. 3. **Performance:** While `measureText()` is highly optimized, calling it repeatedly inside high-frequency animation loops (e.g., `requestAnimationFrame`) can impact performance. Cache measured widths whenever possible if the text and font styles do not change. --- ## Browser Support The basic `measureText().width` property is universally supported across all modern web browsers. | Feature | Chrome | Edge | Firefox | Safari | Opera | Internet Explorer | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | `measureText()` | Yes | Yes | Yes | Yes | Yes | IE 9+ | *Note: Internet Explorer 8 and earlier versions do not support the `` element.*
← Canvas DrawimageCanvas Stroketext β†’