Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
We are implementing a comment functionality on canvas, so for drawing the comment we use a comment image and draw text over it . Could you please let us know how could we get the height and width of the multi-line text written so that we can fit the text inside the image?

What I have tried:

we have tried calculating the height and width by calculating the total no of characters but it fails with different font size
Posted
Updated 14-Mar-22 10:40am

1 solution

Put this text in some other free-size HTML element and render it. For accurate result, you should set the style of this element to have zero padding and borders. Then measure the size of this element using these two HTML element's properties offsetHeight and offsetWidth (sic!).

For a multiline text, this element should be the block element, such as "p" or "div". In this case, there are no predefined width and height, the problem would be ambiguous. Then set it's width by its style to some fixed value you like and measure resulting height. The text will be rendered with word wrapping, automatically, and that will define the height of the outer element.

Problem solved.

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900