Skip to main content

使用字体

以下是您可以在 Remotion 中使用自定义字体的一些方法。

使用 @remotion/google-fonts 导入 Google Fonts

从 v3.2.40 版本开始提供

@remotion/google-fonts 是一种类型安全的方式,可以加载 Google 字体,而无需创建 CSS 文件。

MyComp.tsx
tsx
import { loadFont } from "@remotion/google-fonts/TitanOne";
const { fontFamily } = loadFont();
const GoogleFontsComp: React.FC = () => {
return <div style={{ fontFamily }}>Hello, Google Fonts</div>;
};
MyComp.tsx
tsx
import { loadFont } from "@remotion/google-fonts/TitanOne";
const { fontFamily } = loadFont();
const GoogleFontsComp: React.FC = () => {
return <div style={{ fontFamily }}>Hello, Google Fonts</div>;
};

使用 CSS 导入 Google Fonts

导入 Google Fonts 提供的 CSS。

note

从 2.2 版本开始,Remotion 将自动等待字体加载完成。

font.css
css
@import url("https://fonts.googleapis.com/css2?family=Bangers");
font.css
css
@import url("https://fonts.googleapis.com/css2?family=Bangers");
MyComp.tsx
tsx
import "./font.css";
 
const MyComp: React.FC = () => {
return <div style={{ fontFamily: "Bangers" }}>Hello</div>;
};
MyComp.tsx
tsx
import "./font.css";
 
const MyComp: React.FC = () => {
return <div style={{ fontFamily: "Bangers" }}>Hello</div>;
};

使用 @remotion/fonts 导入本地字体

从 v4.0.164 版本开始提供

将字体放入您的 public/ 文件夹中。
在应用程序中的某个位置执行 loadFont() 调用:

load-fonts.ts
tsx
import { loadFont } from "@remotion/fonts";
import { staticFile } from "remotion";
 
const fontFamily = "Inter";
 
loadFont({
family: fontFamily,
url: staticFile("Inter-Regular.woff2"),
weight: "500",
}).then(() => {
console.log("Font loaded!");
});
load-fonts.ts
tsx
import { loadFont } from "@remotion/fonts";
import { staticFile } from "remotion";
 
const fontFamily = "Inter";
 
loadFont({
family: fontFamily,
url: staticFile("Inter-Regular.woff2"),
weight: "500",
}).then(() => {
console.log("Font loaded!");
});

现在可以使用该字体:

MyComp.tsx
tsx
<div style={{ fontFamily: fontFamily }}>Some text</div>;
MyComp.tsx
tsx
<div style={{ fontFamily: fontFamily }}>Some text</div>;

本地字体(手动)

您可以使用 Web 原生的 FontFace API 加载字体。

load-fonts.ts
tsx
import { continueRender, delayRender, staticFile } from "remotion";
 
const waitForFont = delayRender();
const font = new FontFace(
`Bangers`,
`url('${staticFile("bangers.woff2")}') format('woff2')`,
);
 
font
.load()
.then(() => {
document.fonts.add(font);
continueRender(waitForFont);
})
.catch((err) => console.log("Error loading font", err));
load-fonts.ts
tsx
import { continueRender, delayRender, staticFile } from "remotion";
 
const waitForFont = delayRender();
const font = new FontFace(
`Bangers`,
`url('${staticFile("bangers.woff2")}') format('woff2')`,
);
 
font
.load()
.then(() => {
document.fonts.add(font);
continueRender(waitForFont);
})
.catch((err) => console.log("Error loading font", err));
note

如果您的 TypeScript 类型出现错误,请安装 @types/web 包的最新版本。