Skip to content

🎥 Make videos programmatically with React

best practices

Jonny Burger2c3002d4659a
diff --git a/packages/docs/docs/google-fonts/load-font.md b/packages/docs/docs/google-fonts/load-font.md
index 3490075565..811282fb58 100644
--- a/packages/docs/docs/google-fonts/load-font.md
+++ b/packages/docs/docs/google-fonts/load-font.md
@@ -43,20 +43,27 @@ A large font file paired with a limited bandwith can potentially lead to a rende
If you want to load multiple styles, use multiple `loadFont()` statements.
-```tsx title="Load a specific style, weight and subset"
+```tsx twoslash title="Load a specific style, weight and subset"
+import { AbsoluteFill } from "remotion";
import { fontFamily, loadFont } from "@remotion/google-fonts/Lobster";
-loadFont("normal", {
+const { waitUntilDone } = loadFont("normal", {
weights: ["400"],
subsets: ["latin"],
});
+// Optional: Act once the font has been loaded
+waitUntilDone().then(() => {
+ console.log("Font is loaded");
+});
+
export const GoogleFontsExample: React.FC = () => {
return (
<AbsoluteFill
style={{
justifyContent: "center",
alignItems: "center",
+ // Pass the `fontFamily` you imported as a style
fontFamily: fontFamily,
fontSize: 280,
}}
diff --git a/packages/docs/docs/layout-utils/best-practices.mdx b/packages/docs/docs/layout-utils/best-practices.mdx
new file mode 100644
index 0000000000..dba25ef0a5
--- /dev/null
+++ b/packages/docs/docs/layout-utils/best-practices.mdx
@@ -0,0 +1,90 @@
+---
+image: /generated/articles-docs-layout-utils-best-practices.png
+title: Best practices for @remotion/layout-utils
+sidebar_label: Best practices
+crumb: "@remotion/layout-utils"
+---
+
+Take note of the following points to ensure correct measurements when using the [`@remotion/layout-utils`](/docs/layout-utils) package.
+
+These tips apply to all of [`measureText()`](/docs/layout-utils/measure-text), [`fitText()`](/docs/layout-utils/fit-text), and [`fillTextBox()`](/docs/layout-utils/fill-text-box).
+
+## Wait until the font is loaded
+
+Only call [`measureText()`](/docs/layout-utils/measure-text) after the font is loaded. This applies to Google Fonts (example below) or any other font loading mechanism.
+
+```tsx twoslash title="MyComp.tsx"
+import { useState, useEffect } from "react";
+import { Dimensions, measureText } from "@remotion/layout-utils";
+import { loadFont, fontFamily } from "@remotion/google-fonts/Inter";
+
+const { waitUntilDone } = loadFont("normal");
+
+const MyComp: React.FC = () => {
+ const [dimensions, setDimensions] = useState<Dimensions | null>(null);
+
+ useEffect(() => {
+ // Wait until the font is loaded before measuring text
+ waitUntilDone().then(() => {
+ const measurement = measureText({
+ fontFamily: fontFamily,
+ fontSize: 14,
+ fontWeight: "400",
+ text: "Hello world",
+ });
+
+ // We don't need to use delayRender() here, becuase
+ // font loading from @remotion/google-fonts is already wrapped in it
+ setDimensions(measurement);
+ });
+ }, []);
+
+ return null;
+};
+```
+
+### Use the `validateFontIsLoaded` property<AvailableFrom v="4.0.136"/>
+
+Pass `validateFontIsLoaded: true` to any of [`measureText()`](/docs/layout-utils/measure-text), [`fitText()`](/docs/layout-utils/fit-text), and [`fillTextBox()`](/docs/layout-utils/fill-text-box) to validate that the font family you passed is actually loaded.
+
+This will take a second measurement with the fallback font and if it produces the same measurements, it assumes the fallback font was used and will throw an error.
+
+## Match all font properties
+
+When measuring text, ensure that all font properties match the ones you are going to use in your video.
+This includes `fontFamily`, `fontSize`, and `fontWeight`, `letterSpacing` and `fontVariantNumeric`.
+
+You could make reusable variables that you reference in both the measuring function and the actual component.
+
+```tsx twoslash title="Using variables for font properties"
+import { measureText } from "@remotion/layout-utils";
+
+const text = "Hello world";
+const fontFamily = "Inter";
+const fontWeight = "bold";
+const fontSize = 16;
+
+// Use the variable in the measurement function:
+measureText({
+ text,
+ fontFamily,
+ fontWeight,
+ fontSize,
+});
+
+// As well as in markup
+<div style={{ fontFamily, fontWeight, fontSize }}>{text}</div>;
+```
+
+## Be aware of borders and padding
+
+Adding a `padding` or a `border` to a word will skew the measurements.
+Avoid using `padding` altogether and use the natural spacing between words.
+Instead of `border`, use an `outline` to add a line outside the text without affecting its layout.
+
+## Whitespace
+
+When measuring, the Layout utils will wrap the text in a `<span>` with `display: inline-block` and `white-space: pre` applied.
+This will also measure the width of the whitespace characters.
+
+Add those two CSS properties to your markup as well to match it with the measurements.
diff --git a/packages/docs/docs/layout-utils/fill-text-box.md b/packages/docs/docs/layout-utils/fill-text-box.md
index ea3a3afbbc..0ae0fc60bb 100644
--- a/packages/docs/docs/layout-utils/fill-text-box.md
+++ b/packages/docs/docs/layout-utils/fill-text-box.md
@@ -10,6 +10,24 @@ _Part of the [`@remotion/layout-utils`](/docs/layout-utils) package._
Calculate whether the text exceeds the box and wraps within the container. Only works in the browser, not in Node.js or Bun.
+## Example
+
+```tsx twoslash
+import { fillTextBox } from "@remotion/layout-utils";
+
+const fontFamily = "Arial";
+const fontSize = 12;
+
+const box = fillTextBox({ maxLines: 4, maxBoxWidth: 100 });
+box.add({ text: "Hello", fontFamily, fontSize }); // {exceedsBox: false, newLine: false}
+box.add({ text: "World!", fontFamily, fontSize }); // {exceedsBox: false, newLine: false}
+// Doesn't fit on the previous line anymore
+box.add({ text: "How", fontFamily, fontSize }); // {exceedsBox: false, newLine: true}
+// ...
+// Doesn't fix in the box anymore
+box.add({ text: "the end", fontFamily, fontSize }); // {exceedsBox: true, newLine: false}
+```
+
## API
The function takes the following options:
@@ -62,6 +80,12 @@ _string_
Same as CSS style `font-variant-numeric`.
+#### `validateFontIsLoaded?`<AvailableFrom v="4.0.136"/>
+
+_boolean_
+
+If set to `true`, will take a second measurement with the fallback font and if it produces the same measurements, it assumes the fallback font was used and will throw an error.
+
### Return value
The add method returns an object with two properties:
@@ -71,29 +95,9 @@ The add method returns an object with two properties:
- `newLine`:
_Boolean_, whether adding the word would require starting a new line in the text box.
-## Example
-
-```tsx twoslash
-import { fillTextBox } from "@remotion/layout-utils";
-
-const fontFamily = "Arial";
-const fontSize = 12;
-
-const box = fillTextBox({ maxLines: 4, maxBoxWidth: 100 });
-box.add({ text: "Hello", fontFamily, fontSize }); // {exceedsBox: false, newLine: false}
-box.add({ text: "World!", fontFamily, fontSize }); // {exceedsBox: false, newLine: false}
-// Doesn't fit on the previous line anymore
-box.add({ text: "How", fontFamily, fontSize }); // {exceedsBox: false, newLine: true}
-// ...
-// Doesn't fix in the box anymore
-box.add({ text: "the end", fontFamily, fontSize }); // {exceedsBox: true, newLine: false}
-```
-
## Important considerations
-- The font needs to be loaded before calling `fillTextBox()`.
-- Rendered words should have a `white-space: pre` style to ensure that whitespace is rendered.
-- Consider that `border` and `padding` of the will affect the size of the word. Consider using `outline` instead.
+See [Best practices](/docs/layout-utils/best-practices) to ensure you get correct measurements.
## See also
diff --git a/packages/docs/docs/layout-utils/fit-text.md b/packages/docs/docs/layout-utils/fit-text.md
index 9da40dfd35..2fa9e15f68 100644
--- a/packages/docs/docs/layout-utils/fit-text.md
+++ b/packages/docs/docs/layout-utils/fit-text.md
@@ -77,6 +77,12 @@ _string, optional_
Pass this option if you are going to assign a `font-variant-numeric` CSS property to the text.
+### `validateFontIsLoaded?`<AvailableFrom v="4.0.136"/>
+
+_boolean_
+
+If set to `true`, will take a second measurement with the fallback font and if it produces the same measurements, it assumes the fallback font was used and will throw an error.
+
## Return value
An object with `fontSize` in pixels. Assign this to the `style` prop of your text element.
@@ -138,6 +144,10 @@ Notes:
- The `outline` CSS property was used instead of `border`.
This is because in Remotion, the border is inside by default and shrinks the container, due to `box-sizing: border-box` being in the default stylesheet.
+## Important considerations
+
+See [Best practices](/docs/layout-utils/best-practices) to ensure you get correct measurements.
+
## See also
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/layout-utils/src/layouts/fit-text.ts)
diff --git a/packages/docs/docs/layout-utils/measure-text.md b/packages/docs/docs/layout-utils/measure-text.md
index 5e36db0ce9..4230130d2a 100644
--- a/packages/docs/docs/layout-utils/measure-text.md
+++ b/packages/docs/docs/layout-utils/measure-text.md
@@ -8,6 +8,26 @@ _Part of the [`@remotion/layout-utils`](/docs/layout-utils) package._
Calculates the width and height of specified text to be used for layout calculations. Only works in the browser, not in Node.js or Bun.
+## Example
+
+```tsx twoslash
+import { measureText } from "@remotion/layout-utils";
+
+const text = "remotion";
+const fontFamily = "Arial";
+const fontWeight = "500";
+const fontSize = 12;
+const letterSpacing = "1px";
+
+measureText({
+ text,
+ fontFamily,
+ fontWeight,
+ fontSize,
+ letterSpacing,
+}); // { height: 14, width: 20 }
+```
+
## API
This function has a cache. If there are two duplicate arguments inputs, the second one will return the first result without repeating the calculation.
@@ -50,29 +70,19 @@ _string_
Same as CSS style `font-variant-numeric`.
-## Return value
+### `validateFontIsLoaded?`<AvailableFrom v="4.0.136"/>
-An object with `height` and `width`
+_boolean_
-## Example
+If set to `true`, will take a second measurement with the fallback font and if it produces the same measurements, it assumes the fallback font was used and will throw an error.
-```tsx twoslash
-import { measureText } from "@remotion/layout-utils";
+## Return value
-const text = "remotion";
-const fontFamily = "Arial";
-const fontWeight = "500";
-const fontSize = 12;
-const letterSpacing = "1px";
+An object with `height` and `width`
-measureText({
- text,
- fontFamily,
- fontWeight,
- fontSize,
- letterSpacing,
-}); // { height: 14, width: 20 }
-```
+## Important considerations
+
+See [Best practices](/docs/layout-utils/best-practices) to ensure you get correct measurements.
## See also
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index 12cdae79d2..f74b917650 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -474,6 +474,7 @@ module.exports = {
id: "layout-utils/index",
},
items: [
+ "layout-utils/best-practices",
"layout-utils/measure-text",
"layout-utils/fill-text-box",
"layout-utils/fit-text",
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 6c660bc765..a0970d4225 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1455,6 +1455,13 @@ export const articles = [
compId: "articles-docs-layers",
crumb: "Designing videos",
},
+ {
+ id: "layout-utils/best-practices",
+ title: "Best practices for using @remotion/layout-utils",
+ relativePath: "docs/layout-utils/best-practices.md",
+ compId: "articles-docs-layout-utils-best-practices",
+ crumb: "@remotion/layout-utils",
+ },
{
id: "layout-utils/fill-text-box",
title: "fillTextBox()",
@@ -2201,10 +2208,10 @@ export const articles = [
},
{
id: "recorder/index",
- title: "Introduction",
+ title: "Remotion Recorder",
relativePath: "docs/recorder/index.mdx",
compId: "articles-docs-recorder-index",
- crumb: "Recorder",
+ crumb: "Templates",
},
{
id: "recorder/record",
diff --git a/packages/docs/static/generated/articles-docs-layout-utils-best-practices.png b/packages/docs/static/generated/articles-docs-layout-utils-best-practices.png
new file mode 100644
index 0000000000..1fe15384ec
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-layout-utils-best-practices.png differ
diff --git a/packages/layout-utils/src/index.ts b/packages/layout-utils/src/index.ts
index ce49ef8366..ae83a5ae73 100644
--- a/packages/layout-utils/src/index.ts
+++ b/packages/layout-utils/src/index.ts
@@ -1,3 +1,3 @@
export {fillTextBox} from './layouts/fill-text-box';
export {fitText} from './layouts/fit-text';
-export {measureText} from './layouts/measure-text';
+export {Dimensions, measureText} from './layouts/measure-text';
diff --git a/packages/layout-utils/src/layouts/fill-text-box.ts b/packages/layout-utils/src/layouts/fill-text-box.ts
index a07f611d93..67b4d06a42 100644
--- a/packages/layout-utils/src/layouts/fill-text-box.ts
+++ b/packages/layout-utils/src/layouts/fill-text-box.ts
@@ -17,6 +17,7 @@ export const fillTextBox = ({
fontSize,
letterSpacing,
fontVariantNumeric,
+ validateFontIsLoaded,
}: Word): {
exceedsBox: boolean;
newLine: boolean;
@@ -40,6 +41,7 @@ export const fillTextBox = ({
fontSize,
letterSpacing,
fontVariantNumeric,
+ validateFontIsLoaded,
},
];
diff --git a/packages/layout-utils/src/layouts/fit-text.ts b/packages/layout-utils/src/layouts/fit-text.ts
index 2967031456..771ab395fe 100644
--- a/packages/layout-utils/src/layouts/fit-text.ts
+++ b/packages/layout-utils/src/layouts/fit-text.ts
@@ -9,6 +9,7 @@ export const fitText = ({
fontVariantNumeric,
fontWeight,
letterSpacing,
+ validateFontIsLoaded,
}: {
text: string;
withinWidth: number;
@@ -16,6 +17,7 @@ export const fitText = ({
fontWeight?: number | string;
letterSpacing?: string;
fontVariantNumeric?: string;
+ validateFontIsLoaded?: boolean;
}) => {
const estimate = measureText({
text,
@@ -24,6 +26,7 @@ export const fitText = ({
fontWeight,
fontVariantNumeric,
letterSpacing,
+ validateFontIsLoaded,
});
return {fontSize: (withinWidth / estimate.width) * sampleSize};
};
diff --git a/packages/layout-utils/src/layouts/measure-text.ts b/packages/layout-utils/src/layouts/measure-text.ts
index 6136858fa4..8fba6bc325 100644
--- a/packages/layout-utils/src/layouts/measure-text.ts
+++ b/packages/layout-utils/src/layouts/measure-text.ts
@@ -1,4 +1,4 @@
-type Dimensions = {
+export type Dimensions = {
width: number;
height: number;
};
@@ -10,6 +10,7 @@ export type Word = {
fontWeight?: number | string;
letterSpacing?: string;
fontVariantNumeric?: string;
+ validateFontIsLoaded?: boolean;
};
const wordCache = new Map<string, Dimensions>();
@@ -70,6 +71,7 @@ export const measureText = ({
fontWeight,
letterSpacing,
fontVariantNumeric,
+ validateFontIsLoaded,
}: Word): Dimensions => {
const key = `${text}-${fontFamily}-${fontWeight}-${fontSize}-${letterSpacing}`;
@@ -86,32 +88,32 @@ export const measureText = ({
letterSpacing,
});
- const {
- boundingBox: boundingBoxOfFallbackFont,
- computedFontFamily: computedFallback,
- } = takeMeasurement({
- fontFamily: null,
- fontSize,
- text,
- fontVariantNumeric,
- fontWeight,
- letterSpacing,
- });
-
- const sameAsFallbackFont =
- boundingBox.height === boundingBoxOfFallbackFont.height &&
- boundingBox.width === boundingBoxOfFallbackFont.width;
-
- console.log({sameAsFallbackFont, computedFallback, computedFontFamily});
-
- if (sameAsFallbackFont && computedFallback !== computedFontFamily) {
- const err = [
- `Called measureText() with "fontFamily" ${JSON.stringify(
- fontFamily,
- )} but it looks like the font is not loaded at the time of calling.`,
- `A measurement with the fallback font ${computedFallback} was taken and had the same dimensions, indicating that the browser used the fallback font.`,
- ];
- throw new Error(err.join('\n'));
+ if (validateFontIsLoaded) {
+ const {
+ boundingBox: boundingBoxOfFallbackFont,
+ computedFontFamily: computedFallback,
+ } = takeMeasurement({
+ fontFamily: null,
+ fontSize,
+ text,
+ fontVariantNumeric,
+ fontWeight,
+ letterSpacing,
+ });
+
+ const sameAsFallbackFont =
+ boundingBox.height === boundingBoxOfFallbackFont.height &&
+ boundingBox.width === boundingBoxOfFallbackFont.width;
+
+ if (sameAsFallbackFont && computedFallback !== computedFontFamily) {
+ const err = [
+ `Called measureText() with "fontFamily" ${JSON.stringify(
+ fontFamily,
+ )} but it looks like the font is not loaded at the time of calling.`,
+ `A measurement with the fallback font ${computedFallback} was taken and had the same dimensions, indicating that the browser used the fallback font.`,
+ ];
+ throw new Error(err.join('\n'));
+ }
}
const result = {height: boundingBox.height, width: boundingBox.width};