I have a small problem using Canvas API in HTML5. I have a text that I have to show on a canvas in an html page.
The text example can be "This is an Italic word&
Canvas can measure the width of text in the current font using context.measureText
A Demo: http://jsfiddle.net/m1erickson/S99Zv/
So you can create a function that draws your text and returns the length of text it just drew:
function drawText(text,style,x,y){
if(ctx.font!==style){ctx.font=style;}
ctx.fillText(text,x,y);
return(ctx.measureText(text).width);
}
Then just accumulate the return values to know the x,y of your next block of text:
var style1="20px Sans-Serif";
var style2="italic 20px Sans-Serif";
var accumWidth=30;
accumWidth+=drawText("This is an ",style1,accumWidth,50);
accumWidth+=drawText("italic ",style2,accumWidth,50);
accumWidth+=drawText("word",style1,accumWidth,50);