/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: measureText()

[this page | pdf | back links]

The measureText() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element returns an object indicating the width of the specified text. It can be used to measure the width of some text before it is written onto the canvas

 

The width can be found using the following syntax with the following parameters.

 

context.measureText(text).width

 

Parameter

Required / Optional

Description

text

Required

String specifying text

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>
<br><br>width of text (in pixels) = <span id="x1"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");
c2.fillStyle = "blue";
c2.font = "40px Verdana";
c2.fillText("Hello", 10, 50);
document.getElementById("element").appendChild(x2);
var mText = c2.measureText("Hello");
document.getElementById("x1").innerHTML = 
  mText.width;
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dMeasureText() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.measureText;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile