CanvasRenderingContext2D.measureText()

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

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

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)

参见

文档标签和贡献者

 此页面的贡献者: ice-i-snow
 最后编辑者: ice-i-snow,