Center (proportional font) text in an HTML5 canvas
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 sans-serif';var textString = "Hello look at me!!!", textWidth = ctx.measureText(textString ).width;ctx.fillText(textString , (canvas.width/2) - (textWidth / 2), 100);
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.
developer.mozilla.org states in the textAlign
descriptionthat 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 thosetwo 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);