要獲得HTML5 Canvas的文本度量,我們可以使用的measureText()的畫布上下文的方法 。這種方法需要一個文本字符串,並返回一個度量對象的基礎上提供的文本,並分配給上下文的當前文本的字體。
目前,文本的寬度是唯一的度量與measureText()的方法 。目前還不支持文本的高度公制。
- var metrics = context.measureText(text);
- var width = metrics.width;
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 50px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2 - 10;
var text = "Hello World!";
context.font = "30pt Calibri";
context.textAlign = "center";
context.fillStyle = "blue";
context.fillText(text, x, y);
// get text metrics
var metrics = context.measureText(text);
var width = metrics.width;
context.font = "20pt Calibri";
context.textAlign = "center";
context.fillStyle = "#555";
context.fillText("(" + width + "px wide)", x, y + 40);
};
</script>
</head>
<body onmousedown="return false;">
<canvas id="myCanvas" width="578" height="200">
</canvas>
</body>
</html>