html5 canvas word,HTML5 Canvas API italic word

To achieve some kind of flexibility, you have to decide of a convention inside your text that will tell that the style changed.

And also, you'll have to use measureText to be able to fillText separate 'runs' of the text, each run using the right style, measureText(thisRun).width will give you the size in pixels of the current run.

Then what you need is to draw separate text runs, each in its own style, then move on the 'cursor' based on the return value of measureText.

For a quick example, i took as styling convention "§r" = regular text, "§i" = italic, "§b" = bold, "§l" = lighter, so the string :

var text = "This is an §iItalic§r, a §bbold§r, and a §llighter§r text";

will output as :

5e975e5e5ff845441403d437f5c82d70.png

fiddle is here :

The code is :

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

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;

}

4285477b10157c1a39733d5b2b795fbc.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值