You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.9 KiB
JavaScript
56 lines
1.9 KiB
JavaScript
'use strict';
|
|
|
|
const defaultValue = require("default-value");
|
|
|
|
const findEdge = require("./find-edge");
|
|
const drawCharacter = require("./draw-character");
|
|
const resetCanvas = require("./reset-canvas");
|
|
const createCanvas = require("./create-canvas");
|
|
|
|
module.exports = function measureFont(fontFamily, options = {}) {
|
|
let fontSize = defaultValue(options.fontSize, 20);
|
|
let canvasSize = defaultValue(options.tolerance, 6) * fontSize;
|
|
|
|
let descenderCharacters = ["g", "j", "p", "q", "y"];
|
|
let ascenderCharacters = ["h", "d", "t", "l"];
|
|
let capHeightCharacters = ["H", "I", "T"];
|
|
let medianCharacters = ["x", "v", "w", "z"];
|
|
let topBoundingCharacters = ["O", "A", "8", "#", "%", "^", "!", "/", "|", "]"];
|
|
|
|
let testingCanvas = createCanvas(canvasSize);
|
|
|
|
function getLowest(characters) {
|
|
resetCanvas(testingCanvas);
|
|
|
|
characters.forEach((character) => {
|
|
drawCharacter(testingCanvas, character, fontFamily, fontSize);
|
|
});
|
|
|
|
return findEdge.lowest(testingCanvas);
|
|
}
|
|
|
|
function getHighest(characters) {
|
|
resetCanvas(testingCanvas);
|
|
|
|
characters.forEach((character) => {
|
|
drawCharacter(testingCanvas, character, fontFamily, fontSize);
|
|
});
|
|
|
|
return findEdge.highest(testingCanvas);
|
|
}
|
|
|
|
let lowestDescenderPoint = getLowest(descenderCharacters) - (testingCanvas.height / 2);
|
|
let highestAscenderPoint = (testingCanvas.height / 2) - getHighest(ascenderCharacters);
|
|
let highestCapHeightPoint = (testingCanvas.height / 2) - getHighest(capHeightCharacters);
|
|
let highestMedianPoint = (testingCanvas.height / 2) - getHighest(medianCharacters);
|
|
let highestTopBoundingPoint = (testingCanvas.height / 2) - getHighest(topBoundingCharacters);
|
|
|
|
return {
|
|
descender: lowestDescenderPoint / fontSize,
|
|
ascender: -highestAscenderPoint / fontSize,
|
|
capHeight: -highestCapHeightPoint / fontSize,
|
|
median: -highestMedianPoint / fontSize,
|
|
topBounding: -highestTopBoundingPoint / fontSize
|
|
}
|
|
}
|