我知道我可以使用 context.measureText 来获取某些文本的宽度,如果它现在将呈现在 Canvas 上的话。 有没有办法做同样的事情但得到文本的高度?
只是我自己的一个想法 - 也许我可以将文本旋转 90 度然后测试宽度?...
最佳答案
这个 SO 答案可能针对您的需求进行了过度设计 How can you find the height of text on an HTML canvas?
我更喜欢更简单的东西:
var text = "Hello World";
var font = "Serif";
var size = "16";
var bold = false;
var div = document.createElement("div");
div.innerHTML = text;
div.style.position = 'absolute';
div.style.top = '-9999px';
div.style.left = '-9999px';
div.style.fontFamily = font;
div.style.fontWeight = bold ? 'bold' : 'normal';
div.style.fontSize = size + 'pt'; // or 'px'
document.body.appendChild(div);
var size = [ div.offsetWidth, div.offsetHeight ];
document.body.removeChild(div);
// Output
console.log( size );
var pre = document.getElementById( "output" );
if( pre )
pre.innerHTML = size;
<pre id="output"></pre>
引用: http://www.rgraph.net/blog/2013/january/measuring-text-height-with-html5-canvas.html
关于html - 测量 html5 Canvas 元素上的文本高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11452022/