Created
October 1, 2021 17:04
-
-
Save LukeFinch/56aa7b92359895fe361a77483ae4a8c5 to your computer and use it in GitHub Desktop.
Figma Function to generate font-metrics for use in libraries like SeekOSS Capsize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FontMetrics = { | |
capHeight: number, | |
ascent: number, | |
descent: number, | |
lineGap: number, | |
unitsPerEm: number | |
} | |
async function makeMetrics(fontName: FontName, unitsPerEm: number){ | |
await figma.loadFontAsync(fontName); | |
let fontMetrics: FontMetrics = { | |
capHeight: 0, | |
ascent: 0, | |
descent: 0, | |
lineGap: 0, | |
unitsPerEm: unitsPerEm | |
}; | |
let frame = figma.createFrame() | |
let text = figma.createText() | |
text.fontName = fontName | |
text.characters = "Hg" | |
frame.appendChild(text) | |
text.fontSize = fontMetrics.unitsPerEm | |
text.lineHeight = {unit: "AUTO"} | |
text.x = text.y = frame.x = frame.y = 0 | |
frame.resizeWithoutConstraints(text.width,text.height) | |
//Get cap height | |
let clone = text.clone() | |
clone.characters = "H" | |
let flat = figma.flatten([clone]) | |
frame.appendChild(flat) | |
fontMetrics.capHeight = Number(flat.height.toFixed(2)) | |
//get ascent + descent | |
fontMetrics.ascent = Number((fontMetrics.capHeight + flat.y).toFixed(2)) | |
fontMetrics.descent = Number((frame.height - fontMetrics.ascent).toFixed(2)) | |
frame.remove() | |
return fontMetrics | |
} | |
async function getMetrics(fontName: FontName){ | |
let fontMetrics = await makeMetrics(fontName, 1000) | |
if(!!Object.values(fontMetrics).find((value: number) => !!(value % 1))){ | |
fontMetrics = await makeMetrics(fontName,2048) | |
} | |
return fontMetrics | |
} | |
print(await getMetrics({family: "Roboto", style: "Bold"})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment