--- title: CanvasRenderingContext2D.measureText() slug: Web/API/CanvasRenderingContext2D/measureText tags: - API - Canvas - CanvasRenderingContext2D translation_of: Web/API/CanvasRenderingContext2D/measureText ---
CanvasRenderingContext2D
.measureText()
方法返回一个关于被测量文本{{domxref("TextMetrics")}} 对象包含的信息(例如它的宽度)。
ctx.measureText(text);
{{domxref("TextMetrics")}} 对象。
给出 {{HTMLElement("canvas")}} 元素:
<canvas id="canvas"></canvas>
使用下面的代码,你能得到 {{domxref("TextMetrics")}} 对象:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var text = ctx.measureText("foo"); // TextMetrics object text.width; // 16;
Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-measuretext", "CanvasRenderingContext2D.measureText")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.CanvasRenderingContext2D.measureText")}}