简体   繁体   English

有没有办法用html5 canvas的fillText方法将文本放在不可见的文本框中?

[英]Is there a way to put text in an invisible text box with html5 canvas' fillText method?

I'm making an HTML5 game, and I need a way to textually inform the player about things. 我正在制作HTML5游戏,我需要一种方法以文本方式告知玩家有关事情。 I'd like to put the text in this box, using the fillText method: 我想使用fillText方法将文本放在此框中:

在此处输入图片说明

Now, I only know how to render the text in one line, but that obviously wouldn't suffice, because there need to be linebreaks for the text to fit. 现在,我只知道如何在一行中呈现文本,但这显然是不够的,因为需要换行符才能使文本适合。 Is there a way to do this quickly, or will I have to code it myself? 有什么方法可以快速执行此操作,还是我必须自己编写代码?

This is how a message looks ingame: 这是一条消息在游戏中的外观: 在此处输入图片说明

Looking at the spec , you'll have to do it yourself if you want to use only canvas. 查看规范 ,如果您只想使用画布,则必须自己做。

To do so, you'll need to use measureText in order to get the size of your text and to break it manually. 为此,您需要使用measureText来获取文本的大小并手动将其拆分。 But that seems quite bothersome. 但这似乎很麻烦。

Another solution that I find more elegant is to use an overlay of HTML. 我发现更优雅的另一个解决方案是使用HTML覆盖。 The HTML to use for that could look like that: 用于此的HTML可能如下所示:

<div id="outer" syle="position:relative">
   <canvas id='myCanvas'/>
   <div id="textualDiv" syle="position:absolute"></div>
</div>

You'd then position textualDiv according to your need and you'll just fill it when you'll need it. 然后,您将根据需要定位textualDiv ,并在需要时填充它。 After that you'll just hide it. 之后,您将其隐藏。 And show it again when the need arise. 并在需要时再次显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM