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/
textAlign = "center"; Which should put a text centered both vertically and horizontally.
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.
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!
In the Motion canvas toolbar, select the Text tool, then drag within the text in the canvas.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With