跳转到主内容

离屏渲染

概览

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. Electron中的离屏渲染使用与 Chromium Embedded Framework 项目类似的方法。

注意

  • 有两种渲染模式可以使用(见下),只有未渲染区域传递到 绘图 事件才能提高效率。
  • 您可以停止/继续渲染并设置帧速率。
  • 最高帧速率为 240,因为更高的值只会带来性能上的损失而没有任何收益。
  • 当网页上没有发生任何情况时,不会生成帧。
  • An offscreen window is always created as a Frameless Window.

渲染模式

GPU加速

GPU加速渲染意味着使用GPU用于合成。 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.

  1. Use GPU shared texture

    Used when webPreferences.offscreen.useSharedTexture is set to true.

    This is an advanced feature requiring a native node module to work with your own code. The frames are directly copied in GPU textures, thus this mode is very fast because there's no CPU-GPU memory copies overhead, and you can directly import the shared texture to your own rendering program.

  2. Use CPU shared memory bitmap

    Used when webPreferences.offscreen.useSharedTexture is set to false (default behavior).

    The texture is accessible using the NativeImage API at the cost of performance. The frame has to be copied from the GPU to the CPU bitmap which requires more system resources, thus this mode is slower than the Software output device mode. But it supports GPU related functionalities.

软件输出设备

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.

To enable this mode, GPU acceleration has to be disabled by calling the app.disableHardwareAcceleration() API.

示例

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应用后,进入你的应用的工作目录,你会在里面找到渲染的图片。