Wulin.com (www.vevb.com) Article Introduction: To obtain the text measurement of HTML5 Canvas text, we can use the method of measuringText() canvas context. This method requires a text string and returns a font for the provided text based on a measurement object and assigned to the context's current text.
To get HTML5 Canvas' text metrics we can use the method of the canvas context of measureText(). This method requires a text string and returns a font for the provided text based on a measurement object and assigned to the context's current text.
Currently, the width of the text is the only measure with measureText() method. High metric system of text is not currently supported.
<!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>