如何在边框内填充文本?

2024-05-26 21:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我用谷歌视觉api提取了一些文本。现在的想法是使用边界框中的坐标和尺寸信息在文件上打印文本

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

我试图使用Python脚本在网页上绘制数据。因此,我尝试获取包含文本的跨距的字体大小属性

到目前为止,我已经尝试了使用jQuery的fitText()插件,但它似乎不起作用。有没有其他的办法来获得合适的字体大小


Tags: 文件数据文本脚本api信息网页宽度
1条回答
网友
1楼 · 发布于 2024-05-26 21:54:27

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

&13; 第13部分,;
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>
和#13;
和#13;

相关问题 更多 >

    热门问题