为了实现某种灵活性,您必须在文本中决定一个约定,以表明样式已更改。
而且,您必须使用measureText才能将fillText单独的文本“运行”,每次运行都使用正确的样式,measureText(thisRun).width
将为您提供当前运行的大小(以像素为单位)。
然后,您需要绘制单独的文本串,每个文本串都有自己的样式,然后根据measureText的返回值在“光标”上移动。
举个简单的例子,我将样式约定“§r”=常规文本,“§i”=斜体,“§b”=粗体,“§l”=较浅,所以字符串:
var text = "This is an §iItalic§r, a §bbold§r, and a §llighter§r text";
将输出为:
小提琴在这里:
http://jsfiddle.net/gamealchemist/32QXk/6/ http://jsfiddle.net/gamealchemist/32QXk/6/
代码是:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// marker used in the text to mention style change
var styleMarker = '§';
// table code style --> font style
var styleCodeToStyle = {
r: '',
i: 'italic',
b: 'bold',
l: 'lighter'
};
// example text
var text = "This is an §iItalic§r, a §bbold§r, and a §llighter§r text";
// example draw
drawStyledText(text, 20, 20, 'Sans-Serif', 20);
// example text 2 :
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) {
// start with regular style
var fontCodeStyle = 'r';
do {
// set context font
context.font = buildFont(font, fontSize, fontCodeStyle);
// find longest run of text for current style
var ind = text.indexOf(styleMarker);
// take all text if no more marker
if (ind == -1) ind = text.length;
// fillText current run
var run = text.substring(0, ind);
context.fillText(run, x, y);
// return if ended
if (ind == text.length) return;
// move forward
x += context.measureText(run).width;
// update current style
fontCodeStyle = text[ind + 1];
// keep only remaining part of text
text = text.substring(ind + 2);
} while (text.length > 0)
}
function buildFont(font, fontSize, fontCodeStyle) {
var style = styleCodeToStyle[fontCodeStyle];
return style + ' ' + fontSize + 'px' + ' ' + font;
}