Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 计算数字空格以近似一行文字_Javascript_Reactjs_Text - Fatal编程技术网

Javascript 计算数字空格以近似一行文字

Javascript 计算数字空格以近似一行文字,javascript,reactjs,text,Javascript,Reactjs,Text,我正在制作歌词+和弦显示,我想采用这种原始格式: [Dm]Hello darkness my old [C]friend 把和弦放在歌词上面。我可以通过将每个单词设为div,并使和弦绝对/相对于单词来实现,但这意味着人们无法将所有内容复制并粘贴到所见即所得编辑器(WYSIWYG editor)中 因此,我想在歌词上方画一行,用空格填充,如下所示: Dm C Hello darkness my old friend 使用单空格文本很容易,但我想使用诸如Ar

我正在制作歌词+和弦显示,我想采用这种原始格式:

[Dm]Hello darkness my old [C]friend
把和弦放在歌词上面。我可以通过将每个单词设为div,并使和弦绝对/相对于单词来实现,但这意味着人们无法将所有内容复制并粘贴到所见即所得编辑器(WYSIWYG editor)中

因此,我想在歌词上方画一行,用空格填充,如下所示:

Dm                    C
Hello darkness my old friend
使用单空格文本很容易,但我想使用诸如Arial/Times之类的字体有没有一种方法可以计算出多少空格可以近似于某些文本的长度?

注意:在每个人都说“哦,你应该使用不同的方法来显示和弦”之前,我已经尝试了几种方法,但我特别寻找一些可以复制和粘贴而不会丢失和弦位置的方法。

该界面有一种文本度量方法,可用于获取文本宽度

它需要两个参数,要测量的文本和CSS值

流程中使用的画布元素不必是文档的一部分,也不必具有仅用于使用
measureText
的宽度或高度属性

概念示例:

“严格使用”;
const ctx=document.createElement(“画布”).getContext(“2d”);
函数getTextWidth(text,cssFont){
ctx.font=cssFont;
var o=ctx.measureText(文本);
返回o.width;
}
var cssFont=“14px Arial”;
var spaceWidth=getTextWidth(“,cssFont)/10;
var lyric=“你好,黑暗,我的老朋友”
var lyricWidth=getTextWidth(“你好,我的老朋友”,cssFont);
log('''+lyric+'''+'宽度为'+lyricWidth);
console.log(“空间宽度为”+空间宽度);

log(“所以歌词宽度是“+lyricWidth/spaceWidth+”spaces”)js中有一个方法用于此(measureText)p.s。这个问题已经被问了好几次。。搜索!感谢@RachelGallen的链接,我特别希望空间中的宽度,不仅仅是px,而且这个helpsGlad会有所帮助。我想我在什么地方有小提琴,但现在电脑上没有。你可以用谷歌搜索px到空间的大小吗?