Skip to main content

使用背景图像或遮罩图像时出现闪烁

在 Remotion 中不建议使用以下代码:

❌ 不要这样做
tsx
const myMarkup = (
<div
style={{
backgroundImage: `url(${src})`,
}}
>
<p>Hello World</p>
</div>
);
❌ 不要这样做
tsx
const myMarkup = (
<div
style={{
backgroundImage: `url(${src})`,
}}
>
<p>Hello World</p>
</div>
);

问题

Remotion 无法确定图像何时加载完成,因为通过 background-imagemask-image 或其他 CSS 属性加载图像时无法确定。这将导致 Remotion 在渲染过程中不等待图像加载完成,从而导致可见的闪烁。

解决方案

使用 <Img> 标签,并将其放置在 <AbsoluteFill> 中:

✅ 这样做
tsx
import { AbsoluteFill, Img } from "remotion";
 
const myMarkup = (
<AbsoluteFill>
<AbsoluteFill>
<Img
style={{
width: "100%",
}}
src={src}
/>
</AbsoluteFill>
<AbsoluteFill>
<p>Hello World</p>
</AbsoluteFill>
</AbsoluteFill>
);
✅ 这样做
tsx
import { AbsoluteFill, Img } from "remotion";
 
const myMarkup = (
<AbsoluteFill>
<AbsoluteFill>
<Img
style={{
width: "100%",
}}
src={src}
/>
</AbsoluteFill>
<AbsoluteFill>
<p>Hello World</p>
</AbsoluteFill>
</AbsoluteFill>
);

下一个将放置在图像上方,不会闪烁。

解决方法

如果无法使用 <Img> 标签,例如因为需要使用 mask-image(),则渲染一个渲染相同 src 的相邻 <Img> 标签,并将其放置在视口之外:

✅ 这样做
tsx
import { Img } from "remotion";
 
const myMarkup = (
<>
<Img
src={src}
style={{
opacity: 0,
position: "absolute",
left: "-100%",
}}
/>
<div
style={{
maskImage: `url(${src})`,
}}
>
<p>Hello World</p>
</div>
</>
);
✅ 这样做
tsx
import { Img } from "remotion";
 
const myMarkup = (
<>
<Img
src={src}
style={{
opacity: 0,
position: "absolute",
left: "-100%",
}}
/>
<div
style={{
maskImage: `url(${src})`,
}}
>
<p>Hello World</p>
</div>
</>
);

隐藏的 <Img> 标签确保图像将完全下载,从而使 background-image 完全渲染。

参见