为了实现某种灵活性,您必须在文本中决定一种约定,以表示样式已更改。
并且,您还需要使用measureText来能够填充文本的独立“运行”(即每个运行使用正确的样式),
measureText(thisRun)。width
将给出当前运行的像素大小。
然后,您需要绘制单独的文本运行,每个都有自己的样式,然后根据measureText的返回值移动“光标”。
作为一个快速的例子,我采用了“§r”=常规文本,“§i”=斜体,“§b”=粗体,“§l”=轻字体作为样式约定,因此字符串:
var text = "This is an §iItalic§r, a §bbold§r, and a §llighter§r text"
将输出为:
fiddle 在这里:
http://jsfiddle.net/gamealchemist/32QXk/6/
代码如下:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var styleMarker = '§';
var styleCodeToStyle = {
r: '',
i: 'italic',
b: 'bold',
l: 'lighter'
};
var text = "This is an §iItalic§r, a §bbold§r, and a §llighter§r text";
drawStyledText(text, 20, 20, 'Sans-Serif', 20);
var text2 = "This is a text that has separate styling data";
var boldedWords = [ 3, 5, 8 ];
var italicWords = [ 2, 4 , 7];
var words = text2.split(" ");
var newText ='';
for (var i=0; i<words.length; i++) {
var thisWord = words[i];
if (boldedWords.indexOf(i)!=-1)
newText += '§b' + thisWord + '§r ';
else if (italicWords.indexOf(i)!=-1)
newText += '§i' + thisWord + '§r ';
else
newText += thisWord + ' ';
}
drawStyledText(newText, 20, 60, 'Sans-Serif', 20);
function drawStyledText(text, x, y, font, fontSize) {
var fontCodeStyle = 'r';
do {
context.font = buildFont(font, fontSize, fontCodeStyle);
var ind = text.indexOf(styleMarker);
if (ind == -1) ind = text.length;
var run = text.substring(0, ind);
context.fillText(run, x, y);
if (ind == text.length) return;
x += context.measureText(run).width;
fontCodeStyle = text[ind + 1];
text = text.substring(ind + 2);
} while (text.length > 0)
}
function buildFont(font, fontSize, fontCodeStyle) {
var style = styleCodeToStyle[fontCodeStyle];
return style + ' ' + fontSize + 'px' + ' ' + font;
}