How to center a text in canvas vertically?

Member

by kadin , in category: Javascript , 5 months ago

How to center a text in canvas vertically?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 5 months ago

@kadin 

To center text vertically in a canvas, you can use the textAlign property of the canvas 2D context along with the measureText method to measure the height of the text and then calculate the vertical position accordingly. Here's an example code snippet to center text vertically in a canvas:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var text = 'Centered Text';
var fontSize = 24;
var textWidth = ctx.measureText(text).width;

// Calculate the vertical position to center the text
var x = canvas.width / 2 - textWidth / 2;
var y = canvas.height / 2 + fontSize / 2;

ctx.font = fontSize + 'px Arial';
ctx.textAlign = 'center';

// Center the text horizontally and vertically
ctx.fillText(text, canvas.width/2, canvas.height/2);


In this code snippet, we first measure the width of the text using measureText method. Then, we calculate the x and y positions to center the text both horizontally and vertically. Finally, we set the font size, text alignment, and draw the centered text on the canvas.