js: 访问用户本地字体
枚举本地字体
<button id="btn">Get Local Font</button>
document
.getElementById("btn")
.addEventListener("click", async function () {
const pickedFonts = await window.queryLocalFonts();
for (const fontData of pickedFonts) {
console.log(
`[%o] full name:(%o) family:(%o) style:(%o)`,
fontData.postscriptName,
fontData.fullName,
fontData.family,
fontData.style
);
}
});
使用本地字体设置样式
<button id="btn" style="font-family: dynamic-font">Get Local Font</button>
document
.getElementById("btn")
.addEventListener("click", async function () {
// 请求特定字体
const pickedFonts = await window.queryLocalFonts({
postscriptNames: ["Consolas"],
});
if (!pickedFonts.length) return;
const textStyle = document.createElement("style");
textStyle.textContent = `
@font-face {
font-family: "dynamic-font";
src: local("${pickedFonts[0].postscriptName}");
}`;
document.body.appendChild(textStyle);
});
See also: