TextMetrics.width

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

只读的 TextMetrics.width 属性,包含文本先前的宽度(行内盒子的宽度),使用 CSS 像素计算。

示例

事先给定 <canvas> 元素:

html
<canvas id="canvas"></canvas>

你可以使用下面的代码得到一个 TextMetrics 对象:

js
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var text = ctx.measureText("foo"); // TextMetrics object
text.width; // 16;

规范

Specification
HTML
# dom-textmetrics-width-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
width

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见