Centering text inside a canvas rectangle (button)

canvas, html5-canvas, javascript

Solution

The answer lays mostly in `textAlign="center"` and `textBaseline="middle"`. These two properties align the text in the horizontal space and vertical space respectively.

ctx.lineWidth = 4;
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#abc";
roundRect(ctx, 10, 10, 100, 50, 10, true);
ctx.font="20px Georgia";
ctx.textAlign="center"; 
ctx.textBaseline = "middle";
ctx.fillStyle = "#000000";
var rectHeight = 50;
var rectWidth = 100;
var rectX = 10;
var rectY = 10;
ctx.fillText("Attack!",rectX+(rectWidth/2),rectY+(rectHeight/2));

Demo: http://jsfiddle.net/vu7dZ/4/

Problem

Is there a dynamic way to center the text based on the height, width, X, Y, or a rectangle and the text length? I'm having a bear trying to manually figuring out the X/Y coordinates for a button text. Ignoring that I'm using a method roundRect to make rounded edges, what is a good way to center the text? ``` ctx.lineWidth = 4; ctx.strokeStyle = "#000000"; ctx.fillStyle = "#abc"; roundRect(ctx, 10, 10, 100, 50, 10, true); ctx.font="20px Georgia"; ctx.fillStyle = "#000000"; var rectHeight = 50; var rectWidth = 100; var rectX = 10; var rectY = 10; ctx.fillText("Attack!",rectX+(rectWidth/2),rectY+(rectHeight/2)); ``` See fiddle: http://jsfiddle.net/vu7dZ/1/

Original source