渲染影片工作流程
渲染是將合成影片逐幀捕捉並編碼成影片檔案(例如 MP4)的過程。這是使用 @helios-project/renderer 套件在 Node.js 環境中完成的。
快速路徑:一個指令
npx -y @helios-project/cli@latest render composition.html -o output.mp4
- 時長、FPS 和尺寸來自合成影片的
window.helios。要自行設定,請傳入--duration、--fps、--width和--height。 - 一個使用
window.renderAt(t)自行繪製的頁面需要--duration。 --audio track.mp3可加入配樂。- 純 HTML 檔案會直接從磁碟渲染。如果建置工具需要先建置合成影片,請執行
npm run dev並改傳入其網址。
僅當你需要自訂管道(例如輸入屬性、多個音軌或進度回呼)時,才使用以下腳本。
1. 先決條件
渲染器需要合成影片的網址:
- 磁碟上的檔案:
file:///path/to/composition.html - 開發伺服器:
npm run dev,例如http://localhost:3000/composition.html - 任何其他可存取的網址
2. 建立渲染腳本
建立一個名為 render.js(如果使用 ts-node 則為 render.ts)的檔案。
import { Renderer } from '@helios-project/renderer';
import path from 'path';
async function main() {
// 1. 設定
const compositionUrl = 'http://localhost:3000/composition.html';
const outputPath = path.resolve('output.mp4');
// 2. 初始化渲染器
const renderer = new Renderer({
width: 1920,
height: 1080,
fps: 30,
durationInSeconds: 10,
// frameCount: 300, // 可選:使用精確幀數覆蓋 durationInSeconds
mode: 'canvas', // 如果動畫使用 CSS/HTML 元素,則使用 'dom'
// 音訊設定
audioTracks: [
{ path: 'background.mp3', volume: 0.5 },
{ path: 'voiceover.wav', offset: 2 }
],
audioCodec: 'aac',
// 輸入屬性(動態內容)
inputProps: {
title: "自訂渲染",
color: "#00ff00"
}
});
console.log(`開始渲染 ${compositionUrl}...`);
// 3. 執行渲染
try {
await renderer.render(compositionUrl, outputPath, {
onProgress: (p) => {
const percent = Math.round(p * 100);
process.stdout.write(`\r進度: ${percent}%`);
}
});
console.log(`\n完成!已儲存至 ${outputPath}`);
} catch (err) {
console.error('\n渲染失敗:', err);
process.exit(1);
}
}
main();
3. 執行渲染
執行腳本。
# 如果使用 ts-node
npx ts-node render.ts
# 如果使用 node(已編譯的 js)
node render.js
疑難排解
「頁面逾時」或「連線被拒絕」
- 確保執行合成影片的本機伺服器正在執行。
- 檢查網址是否正確且在一般瀏覽器中可存取。
「黑色輸出」或「空白影片」
- 確保
window.helios已暴露(或頁面定義了window.renderAt(t))。 - 如果使用
mode: 'canvas',確保你正在<canvas>元素上繪圖。 - 如果使用
mode: 'dom',確保元素是可見的。
「渲染卡住」
- 檢查瀏覽器主控台中合成影片是否有錯誤。
- 啟用追蹤以進行除錯:
await renderer.render(url, out, { tracePath: 'trace.zip' });
音訊問題
- 確保音訊檔案路徑相對於腳本執行位置是正確的。
- 如果使用
mode: 'dom'且依賴隱含音訊(例如<audio>標籤),請確保這些元素存在於 DOM 中。