HTML5 Canvas API - formatting individual words with italics

前端 未结 2 1236
走了就别回头了
走了就别回头了 2020-12-11 08:53

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&

2条回答
  •  攒了一身酷
    2020-12-11 09:30

    Canvas can measure the width of text in the current font using context.measureText

    A Demo: http://jsfiddle.net/m1erickson/S99Zv/

    enter image description here

    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);
    

提交回复
热议问题