简体   繁体   English

如何在边界框内放置文本?

[英]How to fit text inside bounding box?

I have extracted some text using Google vision api.我使用 Google vision api 提取了一些文本。 Now the idea is to plot the text on a file using the coordinate and dimensional information from the bounding box.现在的想法是使用来自边界框的坐标和尺寸信息将 plot 文件上的文本。

I have the position and the height and width of the bounding box.我有 position 和边界框的高度和宽度。 Now I need to fit the text inside the box.现在我需要将文本放入框中。 I am not able to obtain the correct font size property that will fit perfectly inside the box.我无法获得完全适合框内的正确字体大小属性。

I am trying to plot the data on a web page using a Python script.我正在尝试使用 Python 脚本 plot web 页面上的数据。 So I am trying to get the font-size property of a span containing the text.所以我试图获取包含文本的跨度的 font-size 属性。

So far I've tried fitText() plugin using jQuery but it doesnt seem to work.到目前为止,我已经尝试使用 jQuery 的 fitText() 插件,但它似乎不起作用。 Any other ideas how to get the appropriate font size?任何其他想法如何获得适当的字体大小?

You could increase the font size as long as its height is less or equal to the bounding box height:只要其高度小于或等于边界框高度,您就可以增加字体大小:

 fitTextInsideBox(document.querySelector('.text'), document.querySelector('.bounding-box')); function fitTextInsideBox(text, box) { // bounding box parameters var boxPosX = 20 var boxPosY = 20; var boxWidth = 500 var boxHeight = 500; box.style.position = 'absolute'; box.style.left = `${boxPosX}px`; box.style.top = `${boxPosY}px`; box.style.width = `${boxWidth}px`; box.style.height = `${boxHeight}px`; text.style.position = 'absolute'; text.style.left = `${boxPosX}px`; text.style.top = `${boxPosY}px`; text.style.width = `${boxWidth}px`; var fontSize = 0; increaseFontSize(text, box); function increaseFontSize(text, box) { fontSize++; text.style.fontSize = `${fontSize}px`; var textHeight = text.getBoundingClientRect().height; if (textHeight <= boxHeight) { increaseFontSize(text, box); } else { fontSize--; text.style.fontSize = `${fontSize}px`; } } }
 body, html { margin: 0; padding: 0; }.bounding-box { border: 2px solid red; box-sizing: border-box; }
 <div class="bounding-box"></div> <span class="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM