Font Leading

Font Leading

by Shakti Patel

HTML

<canvas id="canvas1" width="700" height="200"></canvas>

JavaScript

var text = 'ac';
var font = '50pt Arial';
var metrics = getTextHeight(font, text);
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
ctx.font = font;
ctx.textBaseline = 'top';
ctx.fillText(text, 10, 100);
ctx.strokeRect(10,100,ctx.measureText(text).width,metrics.height);
ctx.moveTo(10, 100+metrics.descent);
ctx.lineTo(ctx.measureText(text).width, 100+metrics.descent);
ctx.stroke();
console.log(metrics.descent)
function getTextHeight(font, s) {
  
  s = s || 'Hg';
  var text = $('<span>'+s+'</span>').css({ font: 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;
};