How to find the height of a text in HTML canvas using JavaScript ?
Last Updated :
12 Jan, 2023
In this article, we will find the height of the text canvas using JavaScript. We have two approaches to find the height of a text in HTML canvas using JavaScript which are described below:
Approach 1: In the following example, the height attribute of the HTML canvas is used. First set the font in pt to set the height.
context.font = '26pt Calibri';
Then the current text is aligned in the center by using values ‘middle’ and color ‘yellow’.
context.textAlign = 'middle';
context.fillStyle = 'yellow';
Then, check the width of the text using the measureText() method before writing to the canvas. Finally, the text is written on the canvas using the fillText() method.
Example: This example shows the use of the above-explained approach.
HTML
< body style = "margin: 0px;padding: 0px;" >
< canvas id = "myCanvas" width = "550" height = "200" >
</ canvas >
< script >
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 3;
var y = canvas.height / 2 - 15;
var text = 'HI ';
// Set the font to set the height
context.font = '26pt Calibri';
context.textAlign = 'middle';
context.fillStyle = 'yellow';
context.fillText(text, x, y);
context.font = '20pt Calibri';
// Check the width of the text
var metrics = context.measureText(text);
var width = metrics.width;
// Text is aligned in the left
context.textAlign = 'left';
context.fillStyle = '#010';
context.fillText('(' + width
+ 'px wide)', x, y + 40);
</ script >
</ body >
|
Output:
Approach 2: First get the 2d drawing context of the canvas by using the getContext() method. Set the font and the text string. Then write the text with x and y co-ordinates using fillText() method as given below.
Example: This example shows the use of the above-explained approach.
HTML
< canvas id = "Canvas" width = "300" ]
height = "150"
style = "border:1px solid #010;" >
Your browser isn't supporting
HTML5 canvas tag.
</ canvas >
< script >
var c = document.getElementById("Canvas");
var x = c.getContext("2d");
x.font = "30px Arial";
var txt = "Computer Science"
x.fillText("width:"
+ x.measureText(txt).width, 10, 50);
x.fillText(txt, 10, 100);
</ script >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...