Remotion LabRemotion Lab
客戶端渲染遷移至客戶端渲染

遷移至客戶端渲染

將現有 Remotion 程式碼遷移至客戶端渲染的指南,包括 API 更換、CORS 設定和媒體元件替換。

遷移至客戶端渲染

警告 — 實驗性功能:此功能隨時可能出現錯誤和重大變更。請在 GitHub 上追蹤進度,並在 Discord 的 #web-renderer 頻道中參與討論。

我們盡量支援為伺服器端渲染所撰寫的程式碼,但部分程式碼不受支援或可能需要修改。

如果你有興趣未來使用客戶端渲染,現在就可以開始對程式碼進行未來相容性調整。

使用 useRemotionEnvironment() 取代 getRemotionEnvironment()

getRemotionEnvironment() 是一個全域 API,當你的專案中同時存在其他 Remotion 執行個體(例如同一頁面上掛載了 <Player>)時,可能會發生衝突。

請改用 useRemotionEnvironment() hook。

使用 useRemotionEnvironment() 取代 getRemotionEnvironment()
// 舊方式(可能導致衝突)
import {getRemotionEnvironment} from 'remotion';
const env = getRemotionEnvironment();
 
// 新方式(推薦)
import {useRemotionEnvironment} from 'remotion';
const MyComponent = () => {
  const env = useRemotionEnvironment();
  return <div>{env.isRendering ? '渲染中' : '預覽中'}</div>;
};

使用 useDelayRender() 取代 delayRender()continueRender()cancelRender()

如果你同時執行多個渲染,或頁面上有另一個 Remotion 執行個體(例如 <Player>),delayRender()continueRender()cancelRender() 函式可能會發生衝突。

請改用 useDelayRender() hook,它會將這些函式的範疇限定於特定組合。

使用 useDelayRender() 取代 delayRender()
// 舊方式(可能在多執行個體時發生衝突)
import {delayRender, continueRender} from 'remotion';
 
const MyComponent = () => {
  useEffect(() => {
    const handle = delayRender();
    fetchData().then(() => {
      continueRender(handle);
    });
  }, []);
  return <div>...</div>;
};
 
// 新方式(範疇限定於組合)
import {useDelayRender} from 'remotion';
 
const MyComponent = () => {
  const [ready, setReady] = useDelayRender();
  useEffect(() => {
    fetchData().then(() => {
      setReady();
    });
  }, []);
  return <div>...</div>;
};

確保資產可透過 CORS 存取

與伺服器端渲染(在 Node.js 程序中下載影片和音訊資產,圖片即使被污染也可捕捉)不同,客戶端渲染強制執行 CORS,圖片和 canvas 不可被污染。

常見錯誤訊息

如果使用了不支援 CORS 的圖片,你會看到如下錯誤:

Could not draw image with src="https://example.com/image.png" to canvas:
The image is tainted due to CORS restrictions.
The server hosting this image must respond with the "Access-Control-Allow-Origin" header.

如果圖片完全無法載入(例如 404 錯誤或無效 URL),你會看到:

Could not draw image with src="https://example.com/image.png" to canvas:
The image is in a broken state.
This usually means the image failed to load - check that the URL is valid and accessible.

解決方案

確保所有圖片、影片和音訊資產的伺服器回應包含適當的 CORS 標頭:

Access-Control-Allow-Origin: *

或限制為你的網域:

Access-Control-Allow-Origin: https://your-domain.com

使用 @remotion/media

唯一受支援的影片和音訊標籤是來自 @remotion/media<Video><Audio>

請將所有 Html5VideoHtml5Audio<OffthreadVideo> 標籤遷移至 <Video><Audio>

遷移媒體元件
// 舊方式(客戶端渲染不支援)
import {OffthreadVideo} from 'remotion';
<OffthreadVideo src="/my-video.mp4" />
 
// 新方式(客戶端渲染支援)
import {Video} from '@remotion/media';
<Video src="/my-video.mp4" />

相關資源