在 HTML5 画布中居中(比例字体)文本 [英] Center (proportional font) text in an HTML5 canvas
问题描述
我希望能够在我可以计算的矩形区域内将单行文本居中.我希望在画布上的 2D 几何中做的一件事是将宽度未知的东西居中.
I would like to be able to center single lines of text within rectangular areas I can calculate. The one thing I have expected to do in 2D geometry on a canvas is to center something whose width is unknown to you.
我听说您可以在 HTML 容器中创建文本,然后调用 jQuery 的 width()
函数作为一种解决方法,但是我没有正确处理文档正文的瞬时添加?并且宽度为 0.
I have heard as a workaround that you can create the text in an HTML container and then call jQuery's width()
function, but I ?didn't correctly handle the momentary addition to the document's body? and got a width of 0.
如果我有一行文本,比填满屏幕的大部分宽度要短得多,我如何知道以我知道的字体大小在画布上有多宽?
If I have a single line of text, significantly shorter than would fill most of the width in a screen, how can I tell how wide it will be on a canvas at a font size I know?
推荐答案
如果你不需要文本的宽度,而只是想让文本居中,你可以这样做
If you don't necesserilly need a width of the text but just want to center text you can do
canvas_context.textBaseline = 'middle';
canvas_context.textAlign = "center";
应该将文本垂直和水平居中.
Which should put a text centered both vertically and horizontally.
这篇关于在 HTML5 画布中居中(比例字体)文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!