Click here to Skip to main content
14,429,185 members
Rate this:
Please Sign up or sign in to vote.
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
Updated 7-Nov-19 6:35am
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.


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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100