font.html
| 1 |
<!DOCTYPE html>
|
|---|---|
| 2 |
<html>
|
| 3 |
<head>
|
| 4 |
<script>
|
| 5 |
window.onload = function()
|
| 6 |
{
|
| 7 |
/*
|
| 8 |
** Module : fontMetrics
|
| 9 |
** Abstract : measure font height.
|
| 10 |
*/
|
| 11 |
var fontMetrics = (function()
|
| 12 |
{
|
| 13 |
var my = {};
|
| 14 |
|
| 15 |
/* canvas height */
|
| 16 |
var height = 200;
|
| 17 |
|
| 18 |
/* canvas width */
|
| 19 |
var width = 500;
|
| 20 |
|
| 21 |
/* canvas use to measure */
|
| 22 |
var fontCanvas;
|
| 23 |
|
| 24 |
/* graphical context */
|
| 25 |
var fontCtx;
|
| 26 |
|
| 27 |
/* get cell height */
|
| 28 |
my.cellHeight = function(font)
|
| 29 |
{
|
| 30 |
|
| 31 |
fontCanvas = document.createElement('canvas');
|
| 32 |
fontCanvas.setAttribute('height', height);
|
| 33 |
fontCanvas.setAttribute('width', width);
|
| 34 |
document.body.appendChild(fontCanvas);
|
| 35 |
fontCanvas.style.position = "absolute";
|
| 36 |
|
| 37 |
fontCtx = fontCanvas.getContext('2d');
|
| 38 |
fontCtx.fillStyle = 'black';
|
| 39 |
fontCtx.fillRect(0, 0, width, height);
|
| 40 |
fontCtx.textBaseline = 'top';
|
| 41 |
fontCtx.fillStyle = 'white';
|
| 42 |
fontCtx.font = font;
|
| 43 |
fontCtx.fillText('QqWwEeRrTtYyUuIiOoPp', 0, 0);
|
| 44 |
|
| 45 |
var pixels = fontCtx.getImageData(0, 0, width, height).data;
|
| 46 |
|
| 47 |
// row numbers where we first find letter end where it ends
|
| 48 |
var beg = -1;
|
| 49 |
var end = -1;
|
| 50 |
|
| 51 |
for (var row = 0; row < height; row++)
|
| 52 |
{
|
| 53 |
for (var col = 0; col < width; col++)
|
| 54 |
{
|
| 55 |
var index = (row * width + col) * 4;
|
| 56 |
// if pixel is not white (background color)
|
| 57 |
if (pixels[index] === 0)
|
| 58 |
{
|
| 59 |
// we havent met white (font color) pixel
|
| 60 |
// on the row and the letters was detected
|
| 61 |
if (col === (width - 1) && beg !== -1)
|
| 62 |
{
|
| 63 |
end = row;
|
| 64 |
row = height;
|
| 65 |
break;
|
| 66 |
}
|
| 67 |
}
|
| 68 |
else
|
| 69 |
{
|
| 70 |
// we find top of letter
|
| 71 |
if (beg === -1)
|
| 72 |
{
|
| 73 |
beg = row;
|
| 74 |
}
|
| 75 |
// ..letters body
|
| 76 |
break;
|
| 77 |
}
|
| 78 |
}
|
| 79 |
}
|
| 80 |
|
| 81 |
/* space at top */
|
| 82 |
my.top = beg;
|
| 83 |
|
| 84 |
/* character height */
|
| 85 |
my.charHeight = end - beg;
|
| 86 |
|
| 87 |
/* cell height top + charHeight */
|
| 88 |
my.cellHeight = end;
|
| 89 |
|
| 90 |
/* cell height */
|
| 91 |
return end;
|
| 92 |
};
|
| 93 |
|
| 94 |
/* exports */
|
| 95 |
return my;
|
| 96 |
})();
|
| 97 |
|
| 98 |
var cellHeight = fontMetrics.cellHeight('20px monospace');
|
| 99 |
|
| 100 |
alert('Top space: ' + fontMetrics.top + '\nCharacter height: ' + fontMetrics.charHeight + "\nCell height: " + cellHeight);
|
| 101 |
|
| 102 |
};
|
| 103 |
</script>
|
| 104 |
</head>
|
| 105 |
<body>
|
| 106 |
<div align="center"> |
| 107 |
<noscript>Your browser does not support JavaScript!</noscript> |
| 108 |
</div>
|
| 109 |
</body>
|
| 110 |
</html>
|