Reputation: 2989
Is there any way to get list of weights for particular font in JavaScript?
I want to build selector like in Photoshop.
Upvotes: 11
Views: 2971
Reputation: 11
You can achieve this using the CSS Font Loading API
The font must be loaded into your document first, using css @font-face
or javascript FontFace
Here is a small example that lists the font weights for all loaded fonts:
document.fonts.ready.then(() => {
const weights = {};
for (const font of document.fonts.values()) {
if (!weights.hasOwnProperty(font.family)) {
weights[font.family] = [];
}
weights[font.family].push(font.weight);
}
console.log(weights);
});
Upvotes: 0
Reputation: 16456
Nope! Whether one typeface is actually a font-weight of another is esoteric knowledge that Javascript has no way of working out. You can define what font-weights a font-family has using CSS @font-face
rules, and in a way this kind of illustrates the impossibility of achieving what you're asking.
Immediately below, I've got a pretty standard @font-face
setup for a font with 3 weights.
@font-face {
font-family: Barney;
src: url(barney_regular.ttf);
font-weight: 400;
}
@font-face {
font-family: Barney;
src: url(barney_light.ttf);
font-weight: 300;
}
@font-face {
font-family: Barney;
src: url(barney_bold.ttf);
font-weight: 500;
}
But knowing that each of those .ttf
files represents a different weight of the same font family is arbitrary. Here I've specified it, because I'm aware of it. If an automated service, eg Font Squirrel, had taken those 3 files, it would probably have come out with this:
@font-face {
font-family: barney_regular;
src: url(barney_regular.ttf);
}
@font-face {
font-family: barney_light;
src: url(barney_light.ttf);
}
@font-face {
font-family: barney_bold;
src: url(barney_bold.ttf);
}
Here, these 3 weights have actually all been specified as distinct font families, which is obviously a mistake. But in theory I could do stupider stuff:
@font-face {
font-family: barney;
src: url(barney_regular.ttf);
font-weight: 500;
}
@font-face {
font-family: barney;
src: url(barney_regular.ttf);
font-weight: 400;
}
@font-face {
font-family: barney;
src: url(barney_regular.ttf);
font-weight: 300;
}
Above, the same exact typeface is being assigned to 3 different weights. So even if Javascript could detect the relationships within @font-face
declarations, like what file is associated with what weight, style & family; how many weights have been specified… It still couldn't tell you whether those resources exist, have been downloaded, accurately represent a different width of the same font.
Web typography has undergone big changes over the past 10 years, but it's still (relatively speaking) a rubbish medium for type-setting.
Upvotes: 2
Reputation: 222
I'm unclear about your end goal, however....
If you are using something like google fonts you should already know all the possible weights available. In other words if you supply your own font then you are the master of all that is available.
Upvotes: 2