Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Canvas measureText() 方法

❮ Canvas 参考

示例

在将文本写入画布之前检查文本的宽度

您的浏览器不支持 HTML5 canvas 标签。

JavaScript

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
let txt = "Hello World"
ctx.fillText("width:" + ctx.measureText(txt).width, 10, 50)
ctx.fillText(txt, 10, 100);
自己试试 »

另请参见

font 属性 (设置文本字体和大小)

fillStyle 属性 (设置文本颜色/渐变)

textAlign 属性 (设置文本对齐)

textBaseline 属性 (设置文本基线)

fillText() 方法 (绘制文本)

strokeText() 方法 (绘制文本)


描述

measureText() 方法返回一个包含指定文本宽度(以像素为单位)的对象。

提示:如果您需要在将文本写入画布之前了解文本的宽度,请使用此方法。

JavaScript 语法 context.measureText(text).width;

参数值

参数 描述 Play it
text 要测量的文本 Play it »

浏览器支持

The <canvas> element is an HTML5 standard (2014).

measureText() is supported in all modern browsers

Chrome Edge Firefox Safari Opera IE
9-11

❮ Canvas 参考
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.