获取画布上多行文字的高度和宽度 [英] Get height and width of multi-line text on canvas

查看:266
本文介绍了获取画布上多行文字的高度和宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在画布上实现评论功能,因此,为了绘制评论,我们使用评论图像并在其上绘制文字。您能否告诉我们如何获得多行文字的高度和宽度,以便我们可以在图像中插入文字?



我尝试了什么:



我们尝试通过计算字符总数来计算高度和宽度但是它会因字体大小不同而失败

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

推荐答案

将此文本放在其他一些可用大小的HTML元素中并进行渲染。为了获得准确的结果,您应该将此元素的样式设置为零填充和边框。然后使用这两个HTML元素的属性 offsetHeight offsetWidth (sic!)来测量此元素的大小。



对于多行文本,此元素应为块元素,例如p或div。在这种情况下,没有预定义的宽度和高度,问题将是模糊的。然后将其宽度按其样式设置为您喜欢的某个固定值并测量结果高度。文本将自动呈现,并自动定义外部元素的高度。



问题解决了。



-SA
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


这篇关于获取画布上多行文字的高度和宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆