2

I have the following canvas:

<canvas id="myCanvas" width="400" height="400" style="border:0px;">
Your browser does not support the HTML5 canvas tag.</canvas>

javascript:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(200, 200, 100, 0, 2 * Math.PI);
ctx.stroke();

I want to write a score within the center of the canvas:

var score = 0;score++;
ctx.fillText(score,200,200);

However this score will be updated and the more digit this value will be the less centered it will be.

I attempted to use the solution offered here, but the "text" here, is merely a javascript variable named score and thus not considered a text.

Here is a fiddle where I played around to try to solve my problem: https://jsfiddle.net/27xfvLhh/

I see two potential way to obtain the result wanted:

  1. Is there a way to fill the text directly centered within my canvas?
  2. Is there a way to calculate what will be the size of the text?

Thanks

user1527152
  • 946
  • 1
  • 13
  • 37

1 Answers1

3

Is there a way to fill the text directly centered within my canvas?

You can use the properties textAlign for horizontal alignment and textBaseline for vertical alignment. Then calculate center point by for example using half the size of the canvas:

Is there a way to calculate what will be the size of the text?

The ctx.measureText("Text").width will give you the width of the text in pixels using the current set font.

var ctx = c.getContext("2d");
ctx.font = "32px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Some Centered Text", ctx.canvas.width>>1, ctx.canvas.height>>1);

// measure text
var width = ctx.measureText("Some Centered Text").width;
ctx.font = "20px sans-serif";
ctx.fillText(width + "px", ctx.canvas.width>>1, 90 + ctx.canvas.height>>1);
#c {border:1px solid}
<canvas id=c width=600 height=300></canvas>