center letters vertically in canvas
by Thanos Saringelos
HTML
<canvas id="canvas1" width="900" height="500"></canvas>
JavaScript
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, 900, 200);
function drawStroked(text, x, y) {
ctx.font = "40px Sans-serif"
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.strokeText(text, x, y);
ctx.fillStyle = 'white';
ctx.fillText(text, x, y);
ctx.fillText(' oAAAAA', x+60, y);
ctx.fillText(' Aooooooo', x+250, y);
ctx.fillText('yg', x+490, y);
ctx.beginPath();
ctx.moveTo(0, 110);
ctx.lineTo(900, 110);
ctx.strokeStyle = '#c2c2d6';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, 70);
ctx.lineTo(900, 70);
ctx.strokeStyle = '#c2c2d6';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, 85);
ctx.lineTo(60, 85);
ctx.strokeStyle = 'yellow';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(90, 87);
ctx.lineTo(260, 87);
ctx.strokeStyle = 'blue';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(260, 90);
ctx.lineTo(470, 90);
ctx.strokeStyle = 'green';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(480, 93);
ctx.lineTo(570, 93);
ctx.strokeStyle = 'purple';
ctx.stroke();
console.log("40px Sans-serif")
}
drawStroked("37°", 0, 100);
var getTextHeight = function(font) {
var text = $('<span>Hg</span>').css({ fontFamily: font });
var block = $('<div style="display: inline-block; width: 1px; height: 0px;"></div>');
var div = $('<div></div>');
div.append(text, block);
var body = $('body');
body.append(div);
try {
var result = {};
block.css({ verticalAlign: 'baseline' });
result.ascent = block.offset().top - text.offset().top;
block.css({ verticalAlign: 'bottom' });
result.height = block.offset().top - text.offset().top;
result.descent = result.height - result.ascent;
} finally {
div.remove();
}
return result;
};