gpt4 book ai didi

javascript - 如何使用 javascript 查找每个字符的宽度(以像素为单位)

转载 作者:行者123 更新时间:2023-12-01 02:02:09 25 4
gpt4 key购买 nike

考虑

<div>manmadhan</div>

我需要知道是否有任何可能的方法可以根据字体找到每个字符的宽度(以像素为单位),因为我使用的是React应用程序,我只需要javascript

输出应类似于 m=12px, n=24 像素类似的东西我尝试分离文本并尝试使用获取边界,但空白区域有一些问题,有什么建议吗?

我已经尝试过以下方法,但它给出的是整个字符串的宽度,而不是字符串中单个字符的宽度 Calculate text width with JavaScript

最佳答案

真正做到这一点的唯一方法是渲染字母,测量它,然后再次删除它。

你可以这样做来在打开页面时获取所有字母,不过最好只在需要时获取长度,甚至不获取长度

let letterLength = {};
let letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

for (let letter of letters) {
let span = document.createElement('span');
span.append(document.createTextNode(letter));
span.style.display = "inline-block";
document.body.append(span);
letterLength[letter] = span.offsetWidth + "px";
span.remove();
}

let word = "manmadhan";

for (let i = 0; i < word.length; i++) {
console.log(word[i] + ": " + letterLength[word[i]])
}

console.log(letterLength)

这并不理想,因为它会使加载时间变慢,所以,正如我所说,如果可以的话,请避免这样做。

警告:

正如利亚姆指出的那样,计算单个字符的宽度可能会失败,导致字符宽度的总和可能等于单词的总宽度。这是因为名为 Kerning 的东西.

In typography, kerning is the process of adjusting the spacing between characters in a proportional font, usually to achieve a visually pleasing result. Kerning adjusts the space between individual letter forms, while tracking (letter-spacing) adjusts spacing uniformly over a range of characters. In a well-kerned font, the two-dimensional blank spaces between each pair of characters all have a visually similar area.

下面是一个示例,它将 span 的宽度与 in 中的整个单词的宽度与其独立字母的总和进行比较。

let letterLength = {};
let letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

for (let letter of letters) {
let span = document.createElement('span');
span.append(document.createTextNode(letter));
span.style.display = "inline-block";
document.body.append(span);
letterLength[letter] = span.offsetWidth;
span.remove();
}


let word = document.querySelector(".word");
let totalLength = 0;
let actualLength = word.offsetWidth

for (let i = 0; i < word.innerHTML.length; i++) {
totalLength += letterLength[word.innerHTML[i]];
}
console.log("span: "+actualLength+"px");
console.log("letters: "+totalLength+"px");
.word {
display: inline-block;
}
<span class="word">Averages</span>

我希望这能回答您的问题。

关于javascript - 如何使用 javascript 查找每个字符的宽度(以像素为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com