跳至主要內容

離屏渲染

概述

離屏渲染允許您取得 BrowserWindow 的內容,以點陣圖或共享 GPU 紋理的形式呈現,因此可以在任何地方渲染,例如在 3D 場景中的紋理上。Electron 中的離屏渲染使用與 Chromium Embedded Framework 專案類似的方法。

注意事項:

  • 可以使用兩種渲染模式(請參閱以下章節),並且只有髒區會傳遞到 paint 事件以提高效率。
  • 您可以停止/繼續渲染以及設定幀率。
  • 最大幀率為 240,因為更大的值只會帶來效能損失,而沒有任何好處。
  • 當網頁上沒有任何動作時,不會產生任何幀。
  • 離屏視窗始終會建立為無邊框視窗

渲染模式

GPU 加速

GPU 加速渲染表示 GPU 用於合成。此模式的好處是支援 WebGL 和 3D CSS 動畫。根據 webPreferences.offscreen.useSharedTexture 設定,有兩種不同的方法。

  1. 使用 GPU 共享紋理

    webPreferences.offscreen.useSharedTexture 設定為 true 時使用。

    這是一項進階功能,需要原生 Node 模組才能與您自己的程式碼一起使用。幀會直接複製到 GPU 紋理中,因此這種模式非常快,因為沒有 CPU-GPU 記憶體複製的開銷,並且您可以直接將共享紋理匯入您自己的渲染程式。

  2. 使用 CPU 共享記憶體點陣圖

    webPreferences.offscreen.useSharedTexture 設定為 false 時使用(預設行為)。

    可以使用 NativeImage API 存取紋理,但會犧牲效能。幀必須從 GPU 複製到 CPU 點陣圖,這需要更多系統資源,因此這種模式比軟體輸出裝置模式慢。但它支援 GPU 相關的功能。

軟體輸出裝置

此模式使用軟體輸出裝置在 CPU 中進行渲染,因此幀產生速度比共享記憶體點陣圖 GPU 加速模式更快。

若要啟用此模式,必須呼叫 app.disableHardwareAcceleration() API 來停用 GPU 加速。

範例

const { app, BrowserWindow } = require('electron/main')
const fs = require('node:fs')
const path = require('node:path')

app.disableHardwareAcceleration()

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
offscreen: true
}
})

win.loadURL('https://github.com')
win.webContents.on('paint', (event, dirty, image) => {
fs.writeFileSync('ex.png', image.toPNG())
})
win.webContents.setFrameRate(60)
console.log(`The screenshot has been successfully saved to ${path.join(process.cwd(), 'ex.png')}`)
}

app.whenReady().then(() => {
createWindow()

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

啟動 Electron 應用程式後,導覽至應用程式的工作資料夾,您會在其中找到渲染的影像。