0 0 Votes

HTML5 Canvas: Center Text on Point horizontally and vertically

Tutorial by Stefan Trost | 19/06/2014 at 15:57

In this tutorial, I would like to show you how you can center a text horizontally and vertically on an HTML 5 canvas. In other words, the text should be placed just in the middle of a given point.

First, we define a canvas in HTML.

<canvas id="canv" width="200" height="200"></canvas>

After that, we are adding the following JavaScript:

var canvas = document.getElementById('canv');
var context = canvas.getContext('2d');

var x = 100;
var y = 100; 

context.font = '20px Verdana';
context.fillStyle = '#000000';
context.textAlign = 'center';
context.textBaseline = 'middle'; 
context.fillText('Text', x, y);

We would like to place our text exactly in the middle of our 200 x 200 pixel canvas. This corresponds to the point 100/100 in the coordinate system. In the example above, we have defined the variables x and y for this point.

After that, we are defining font size and name via context.font and the filling, that is the font color, via context.fillStyle.

The actual centering is done in the next two lines. Using the property textAlign, you can adjust the horizontal alignment, textBaseline can be used to specify the vertical. By setting the horizontal alignment to "center" and the vertical alignment to "middle", our text is centered exactly in the middle of the given point.

Subsequently, the output of the text is carried out with fillText. We can just pass the text we would like to write (here "Text") and the coordinates to this function. The function always uses the last styles defined before.

Other Property Values of textAlign and textBaseline

Beyond "center", you can also use "left" or "right" for the horizontal alignment, to let the text start or end at the provided x coordinate.

The vertical alignment with textBaseline, can also be set to "bottom" or "top" to adjust the text at the top or the bottom off its complete height. "alphabetic" and "hanging" align the text from the bottom or the top at letters like a, c or e while "ideographic" aligns the text at the ideographic baseline under the alphabetic.

ReplyPositiveNegative

About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.