Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering text inside a canvas rectangle (button)

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/

like image 260
bo_knows Avatar asked Jul 04 '14 01:07

bo_knows


People also ask

How do I center align text in canvas?

textAlign = "center"; Which should put a text centered both vertically and horizontally.

How do I center content in canvas?

Complete HTML/CSS Course 2022 To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned.

How do you write text in a rectangle in canvas?

fillRect(0, 0, 50, 50); ctx. fillText(text, 10, 10); This will place a rectangle at (0, 0) and will end at (50, 50) and the text fill be placed at (10, 10). You can also use the font property to set the font of the text. Hope that helps!

How do I move text in canvas?

In the Motion canvas toolbar, select the Text tool, then drag within the text in the canvas.


1 Answers

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/

like image 64
bo_knows Avatar answered Sep 30 '22 05:09

bo_knows