Center (proportional font) text in an HTML5 canvas

后端 未结 5 1291
别那么骄傲
别那么骄傲 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

    0 讨论(0)
  • 2020-12-18 20:09

    You can use ctx.textAlign = "center"; to align item to center

    var canva = document.getElementById("canvas");
    ctx.textAlign = "center"; // To Align Center
    ctx.font = "40px Arial"; // To change font size and type
    ctx.fillStyle = '#313439'; // To give font 
    ctx.fillText("Text Center", 150 ,80);
    
    0 讨论(0)
  • 2020-12-18 20:10

    If you don't necesserilly need a width of the text but just want to center text you can do

      canvas_context.textBaseline = 'middle';
      canvas_context.textAlign = "center";
    

    Which should put a text centered both vertically and horizontally.

    0 讨论(0)
  • 2020-12-18 20:13

    developer.mozilla.org states in the textAlign description that the alignment is based on the x value of the context's fillText() method. That is, the property does not center the text in the canvas horizontally; it centers the text around the given x coordinate. Similar applies for the textBaseLine.

    So in order to center the text in both directions, we need to set those two properties and position the text in the middle of the canvas.

    ctx.textBaseline = 'middle'; 
    ctx.textAlign = 'center'; 
    
    ctx.fillText('Game over', canvas_width/2, canvas_height/2);
    
    0 讨论(0)
  • 2020-12-18 20:16

    What you do is render your text off-screen using a negative text-indent, then grab the size.

    text-indent: -9999px
    

    See: hiding text using "text-indent"

    0 讨论(0)
提交回复
热议问题