CanvasRenderingContext2D.measureText() 方法返回一个 TextMetrics 对象,包含关于文本尺寸的信息(例如文本的宽度)。
语法
ctx.measureText(text);
参数
- text
- 需要测量的文本。
返回值
TextMetrics 对象。
示例
已有 <canvas> 元素:
<canvas id="canvas"></canvas>
使用下面的代码,你能得到 TextMetrics 对象:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var text = ctx.measureText("foo"); // TextMetrics object
text.width; // 16;
规范描述
| Specification | Status | Comment |
|---|---|---|
| WHATWG HTML Living Standard CanvasRenderingContext2D.measureText |
Living Standard |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | 9 | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |