离屏渲染
🌐 Offscreen Rendering
概述
🌐 Overview
离屏渲染允许你获取 BrowserWindow 的内容到位图或共享 GPU 纹理中,因此可以在任何地方进行渲染,例如在 3D 场景中的纹理上。Electron 中的离屏渲染使用了与 Chromium Embedded Framework 项目类似的方法。
🌐 Offscreen rendering lets you obtain the content of a BrowserWindow in a
bitmap or a shared GPU texture, so it can be rendered anywhere, for example,
on texture in a 3D scene.
The offscreen rendering in Electron uses a similar approach to that of the
Chromium Embedded Framework
project.
注意:
🌐 Notes:
- 有两种可以使用的渲染模式(见下文),并且只有脏区域会传递给
paint事件,以提高效率。 - 你可以停止/继续渲染以及设置帧速率。
- 当
webPreferences.offscreen.useSharedTexture为false时,最大帧率为 240,因为更高的数值只会带来性能损失而没有任何好处。 - 当网页上没有发生任何事情时,不会生成任何框架。
- 离屏窗口总是作为无边框窗口创建的。
渲染模式
🌐 Rendering Modes
GPU 加速
🌐 GPU accelerated
GPU 加速渲染意味着使用 GPU 进行合成。这种模式的好处是支持 WebGL 和 3D CSS 动画。根据 webPreferences.offscreen.useSharedTexture 设置,有两种不同的方法。
🌐 GPU accelerated rendering means that the GPU is used for composition. The benefit
of this mode is that WebGL and 3D CSS animations are supported. There are two
different approaches depending on the webPreferences.offscreen.useSharedTexture
setting.
-
使用 GPU 共享纹理
当
webPreferences.offscreen.useSharedTexture设置为true时使用。这是一个高级功能,需要本地节点模块才能与你自己的代码配合使用。帧会直接复制到 GPU 纹理中,因此这种模式非常快,因为没有 CPU 和 GPU 内存复制的开销,并且你可以将共享纹理直接导入到自己的渲染程序中。你可以在这里阅读更多详细信息。
-
使用 CPU 共享内存位图
当
webPreferences.offscreen.useSharedTexture设置为false时使用(默认行为)。可以通过
NativeImageAPI 访问纹理,但代价是性能降低。帧必须从 GPU 复制到 CPU 位图,这需要更多的系统资源,因此这种模式比软件输出设备模式更慢。但它支持与 GPU 相关的功能。
软件输出设备
🌐 Software output device
此模式使用软件输出设备在 CPU 中进行渲染,因此帧生成速度比共享内存位图 GPU 加速模式更快。
🌐 This mode uses a software output device for rendering in the CPU, so the frame generation is faster than shared memory bitmap GPU accelerated mode.
要启用此模式,必须通过调用 app.disableHardwareAcceleration() API 禁用 GPU 加速。
🌐 To enable this mode, GPU acceleration has to be disabled by calling the
app.disableHardwareAcceleration() API.
示例
🌐 Example
- main.js
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 应用后,导航到应用的工作文件夹,在那里你会找到渲染后的图片。
🌐 After launching the Electron application, navigate to your application's working folder, where you'll find the rendered image.