【发布时间】:2013-10-28 05:26:44
【问题描述】:
下面是一个数组,它的元素存储了一些长文本行。
var fcontent = [
["Definition: The term computer is obtained from the word compute. A computer is an electronic device that inputs (takes in) facts (known as data), and then processes (does something to or with) it. Afterwards it outputs, or displays, the results for you to see. Data is all kinds of facts, including, pictures, letters, numbers, sounds, etc."],
["Moreover: A computer is a system that is made up of a number of components. Next is a diagram of a computer system with some of its components"],
];
我正在使用以下函数在 Canvas 上显示元素:
firstLevelContent:function()
{
var startPoint = 48; $('.gamelayer').hide();
$('#gamecanvas').show();
for (var i=0; i<fcontent.length; i++)
{
game.context.strokeRect(1, 25, 637, 385);
game.context.fillStyle = 'brown';
game.context.font = 'bold 20px sans-serif';
game.context.textBaseline = 'bottom';
game.context.fillText(fcontent[i], 2, startPoint);
startPoint+=17;
}
},
但是文本显示在代码中,我想找到一种方法来换行以适应画布的宽度(640),以便我可以看到所有显示的文本。请帮助我。谢谢。
【问题讨论】:
-
这不是 JavaScript 问题。您需要做的就是在 css 中为画布指定宽度。你能告诉我你用于画布的CSS吗?如果有正确的 css 类,文本将自动适合他的宽度。
-
@GeorgianBurungiu。不,html 画布不会自动应用换行符以使文本适合画布宽度。
-
您必须使用 javascript 手动进行文本换行。您可以使用 context.measureText 方法来获取每个单词的宽度。当累积的单词超过画布长度时,开始换行。查看以前的 Stackoverflow 答案,了解如何在 html 画布上将文本换行到多行:stackoverflow.com/questions/2936112/…