有没有办法在JavaScript中获取特定字体的权重列表?
我想要构建像Photoshop中的选择器。
有没有办法在JavaScript中获取特定字体的权重列表?
我想要构建像Photoshop中的选择器。
不行!一个字体是否是另一个字体的字重是深奥的知识,Javascript 无法解决这个问题。你可以使用 CSS @font-face
规则来定义字体族中有哪些字重,并且从某种程度上来说,这说明了你所要求的是不可能实现的。
下面是一个拥有 3 种字重的标准 @font-face
设置。
@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;
}
.ttf
文件代表同一字体族的不同粗细是任意的。在这里我已经指定了它,因为我很清楚。如果一个自动化服务,比如Font Squirrel,获取了这3个文件,它可能会得出这样的结果:@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);
}
在这里,这三个字重实际上都被定义为不同的字体系列,显然是一个错误。但理论上我可以做更愚蠢的事情:
@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;
}
@font-face
声明中的关系,例如哪个文件与哪个字重、样式和字族相关联;有多少个字重已经被指定...... 它仍然无法告诉您这些资源是否存在,是否已经下载,是否准确地表示了同一字体的不同宽度。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);
});