Center (proportional font) text in an HTML5 canvas

后端 未结 5 1295
别那么骄傲
别那么骄傲 2020-12-18 19:41

I would like to be able to center single lines of text within rectangular areas I can calculate. The one thing I have expected to do in 2D geometry on a canvas is to center

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 20:03

    You can do this by using measureText

    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d")
    
    canvas.width = 400;
    canvas.height = 200;
    
    ctx.fillStyle = "#003300";
    ctx.font = '20px san-serif';
    
    var textString = "Hello look at me!!!",
        textWidth = ctx.measureText(textString ).width;
    
    
    ctx.fillText(textString , (canvas.width/2) - (textWidth / 2), 100);
    

    Live Demo

    More elaborate demo

提交回复
热议问题