Centering text inside a canvas rectangle (button)
15,194
The answer lays mostly in textAlign="center" and textBaseline="middle". These 2 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/
Author by
bo_knows
Updated on July 30, 2022Comments
-
bo_knows over 1 year
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/
-
Si8 over 5 yearsWhat if the rectangle is horizontally centered in the canvas itself?
-
F.K over 2 yearsPrecisely what I was looking for