CanvasRenderingContext2D.measureText()

CanvasRenderingContext2D.measureText() 方法返回一个关于被测量文本TextMetrics 对象包含的信息(例如它的宽度)。

语法

ctx.measureText(text);

参数

text
需要测量的String 。

返回值

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
HTML Living Standard
CanvasRenderingContext2D.measureText
Living Standard  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
measureTextChrome Full support YesEdge Full support 12Firefox Full support 2IE Full support 9Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support

参见