首页 > 解决方案 > 如何在边界框内放置文本?

问题描述

我使用 Google vision api 提取了一些文本。现在的想法是使用来自边界框的坐标和尺寸信息在文件上绘制文本。

我有边界框的位置和高度和宽度。现在我需要将文本放入框中。我无法获得完全适合框内的正确字体大小属性。

我正在尝试使用 Python 脚本在网页上绘制数据。所以我试图获取包含文本的跨度的 font-size 属性。

到目前为止,我已经尝试过使用 jQuery 的 fitText() 插件,但它似乎不起作用。任何其他想法如何获得适当的字体大小?

标签: javascriptpythonhtmlcsscomputer-vision

解决方案


只要其高度小于或等于边界框高度,您就可以增加字体大小:

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>


推荐阅读