如何在sveltekit中加载本地字体?

问题描述 投票:0回答:1

尝试在 sveltekit 中使用这些 fonts 但不起作用,其他字体似乎可以工作,应该可以工作我通过加载

localFont
(特定于 nextjs)在 nextjs 应用程序中测试它们,因此该字体没有损坏,

尝试在css文件中定义字体系列,如下所示:

@font-face {
    font-family: 'P1';
    src: url('/fonts/quran/pages/p1.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
    font-display: swap;
}

通过在顺风配置和内联样式中定义来尝试它

style="font-family: P1;"
,没有工作

尝试使用如下js加载,但也不起作用,尽管我看到字体被添加到

document.fonts
并将font-family设置为目标元素:

export const loadQuranPageFont = async (pageNumber: number) => {
    const fontName = `quran-page-${pageNumber}`;
    const fontUrl = `/fonts/quran/pages/p${pageNumber}.woff2`; // 'fonts' is located in the static folder, also tried to put inside 'src/lib' folder and call it like '$lib/fonts/..' either didn't make difference

    const fontFace = new FontFace(fontName, `url(${fontUrl})`);

    try {
        // Load and add the font
        const loadedFont = await fontFace.load();
        document.fonts.add(loadedFont);

        // Set the CSS variable for use
        const element = document.getElementById('quran');
        element.style.fontFamily = fontName;
        console.log(`Font for page ${pageNumber} loaded and set to CSS variable.`);
    } catch (err) {
        console.error("[Couldn't load font]: ", err);
    }
};
fonts svelte sveltekit
1个回答
0
投票

/
路径对于 Vite 来说不明确/不会作为资产包含在构建输出中。
使用相对路径导入或从
$lib
.

导入
@font-face {
  /* Navigate using ./ or ../ paths. */
  src: url('../../lib/quran/pages/p1.woff2') format('woff2');
}
@font-face {
  /* $lib points to src/lib directory */
  src: url('$lib/quran/pages/p1.woff2') format('woff2');
}
© www.soinside.com 2019 - 2024. All rights reserved.