javascript 在 HTML5 画布中居中(比例字体)文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13771310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center (proportional font) text in an HTML5 canvas
提问by Christos Hayward
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.
我希望能够在我可以计算的矩形区域内将单行文本居中。我希望在画布上的 2D 几何中做的一件事是将宽度未知的东西居中。
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.
我听说您可以在 HTML 容器中创建文本然后调用 jQuery 的 width() 函数作为一种解决方法,但是我没有正确处理文档正文的瞬时添加?并且宽度为 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?
如果我有一行文本,比填满屏幕的大部分宽度要短得多,我怎么知道它在画布上以我知道的字体大小有多宽?
TIA,
TIA,
回答by Loktar
You can do this by using measureText
您可以使用measureText做到这一点
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d")
canvas.width = 400;
canvas.height = 200;
ctx.fillStyle = "#003300";
ctx.font = '20px san-serif';
var textString = "Hello look at me!!!",
textWidth = ctx.measureText(textString ).width;
ctx.fillText(textString , (canvas.width/2) - (textWidth / 2), 100);
回答by Marcin Raczkowski
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.
这应该将文本垂直和水平居中。
回答by Jan Bodnar
developer.mozilla.orgstates in the textAlign
description
that the alignment is based on the x valueof the context's fillText()
method. That is, the property does not center the text in the canvas horizontally; it centers the text around the given x coordinate. Similar applies for the textBaseLine
.
developer.mozilla.org在textAlign
描述中指出对齐基于上下文方法的 x 值fillText()
。也就是说,该属性不会将画布中的文本水平居中;它将文本围绕给定的 x 坐标居中。类似适用于textBaseLine
.
So in order to center the text in both directions, we need to set those two properties and position the text in the middle of the canvas.
因此,为了使文本在两个方向上居中,我们需要设置这两个属性并将文本放置在画布的中间。
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillText('Game over', canvas_width/2, canvas_height/2);
回答by Diodeus - James MacFarlane
What you do is render your text off-screen using a negative text-indent, then grab the size.
您所做的是使用负文本缩进在屏幕外渲染文本,然后获取大小。
text-indent: -9999px
See: hiding text using "text-indent"
请参阅:使用“文本缩进”隐藏文本