中心(比例字体)文本在HTML5画布中 [英] Center (proportional font) text in an HTML5 canvas

查看:287
本文介绍了中心(比例字体)文本在HTML5画布中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要能够计算矩形区域中的单行文本。我想要在画布上的二维几何中做一件事,就是将你的未知的宽度对中。

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?

TIA,

推荐答案

如果你不需要文本的宽度,但只是想要中心的文本,你可以做

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆