What I am trying to do is display multiple lines of text in the middle of a canvas element. The text is dynamic as it is inputted by the user using a text box, the canvas is then updated with the text the user has typed (code shown below). I would like the text to appear on the canvas in a similar fashion to the way that the text would appear using vertical-align: middle property in CSS. My question is what would be the easiest way to approach this problem.
A big issue that I am having is that the user can change the font. As different fonts are different heights (even if they are defined at a px height they are not consistently that height). The best idea I have had so far is to calculate the height of the text on the canvas. I read this article on the site How can you find the height of text on an HTML canvas?, see the second answer by Daniel. This should calculate the actual height of the text which can then be used to calculate the correct starting position of the text to center it on the canvas. Based on my code below I believe I would have to essentially run a similar code to predetermine the correct starting position of the font.
This is my approach to properly wrap and display the text on the canvas:
function wrapText(context, text, x, y, maxWidth, lineHeight) {
//manage carriage return
text = text.replace(/(\r\n|\n\r|\r|\n)/g, "\n");
//manage tabulation
text = text.replace(/(\t)/g, " "); // I use 4 spaces for tabulation, but you can use anything you want
//array of lines
var sections = text.split("\n");
for (s = 0, len = sections.length; s < len; s++) {
var words = sections[s].split(' ');
var line = '';
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
//new line for new section of the text
y += lineHeight;
}
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var maxWidth = 350;
var lineHeight = 25;
var x = (canvas.width - maxWidth) / 2;
var y = 60;
var text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. \nLorem Ipsum has been the industry's standard dummy text ever since the 1500s.";
context.font = '14pt Verdana';
context.fillStyle = '#000';
wrapText(context, text, x, y, maxWidth, lineHeight);
I am wondering if there is another approach that I have not considered that would simplify the problem or whether this approach is the best one to take? Is is a simpler way on a canvas element to vertical-align text similar to CSS?