javascript - 如何在边界框内放置文本?
问题描述
我使用 Google vision api 提取了一些文本。现在的想法是使用来自边界框的坐标和尺寸信息在文件上绘制文本。
我有边界框的位置和高度和宽度。现在我需要将文本放入框中。我无法获得完全适合框内的正确字体大小属性。
我正在尝试使用 Python 脚本在网页上绘制数据。所以我试图获取包含文本的跨度的 font-size 属性。
到目前为止,我已经尝试过使用 jQuery 的 fitText() 插件,但它似乎不起作用。任何其他想法如何获得适当的字体大小?
解决方案
只要其高度小于或等于边界框高度,您就可以增加字体大小:
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>
推荐阅读
- google-translate - 翻译不带空格的网址
- azure-active-directory - 在 Azure AD 中存储机密数据
- python - python 请求:对天蓝色的 PUT 请求失败并出现 415 错误
- csv - 即使在 12 小时后也没有完成加载 csv 的查询
- python - Alexa 中位置服务的端点是什么?
- sql - SQL Server - 带有变量和 SUM() 方法的 SELECT 语句
- amazon-web-services - Dynamodb 成本与 Aurora 成本比较
- windows - Windows和嵌入式系统(STM32)之间的串行通信数据问题(C/C++)
- postgresql - 与原始数据库相比,还原转储的物化视图上的搜索查询速度较慢
- node.js - 在编排中捕获错误后未执行活动