CanvasRenderingContext2D: measureText() method
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{APIRef("Canvas API")}}
The CanvasRenderingContext2D.measureText() method returns a {{domxref("TextMetrics")}} object that contains information about the measured text (such as its width, for example).
Syntax
js-nolint
measureText(text)Parameters
text- : The text string to measure.
Return value
A {{domxref("TextMetrics")}} object.
Examples
Given this {{HTMLElement("canvas")}} element:
html
<canvas id="canvas"></canvas>… you can get a {{domxref("TextMetrics")}} object using the following code:
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let text = ctx.measureText("Hello world");
console.log(text.width); // 56;Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
- {{domxref("TextMetrics")}}