CanvasRenderingContext2D:measureText() 方法
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.
CanvasRenderingContext2D.measureText()
方法返回一个包含被测量文本相关信息(例如它的宽度)的 TextMetrics
对象。
语法
js
measureText(text)
参数
text
-
需要测量的文本字符串。
返回值
TextMetrics
对象。
示例
给定 <canvas>
元素:
html
<canvas id="canvas"></canvas>
使用下面的代码,你能得到 TextMetrics
对象:
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let text = ctx.measureText("Hello world");
console.log(text.width); // 56;
规范
Specification |
---|
HTML Standard # dom-context-2d-measuretext-dev |
浏览器兼容性
BCD tables only load in the browser
参见
- 定义此方法的接口:
CanvasRenderingContext2D
TextMetrics