Skip to main content

离屏渲染

¥Offscreen Rendering

概述

¥Overview

离屏渲染允许你获取位图中 BrowserWindow 的内容,因此可以在任何位置渲染它,例如,在 3D 场景中的纹理上。Electron 中的离屏渲染使用与 Chrom 嵌入式框架 项目类似的方法。

¥Offscreen rendering lets you obtain the content of a BrowserWindow in a bitmap, 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 事件以提高效率。

    ¥There are two rendering modes that can be used (see the section below) and only the dirty area is passed to the paint event to be more efficient.

  • 你可以停止/继续渲染以及设置帧速率。

    ¥You can stop/continue the rendering as well as set the frame rate.

  • 最大帧速率为 240,因为更大的值只会带来性能损失,而没有任何好处。

    ¥The maximum frame rate is 240 because greater values bring only performance losses with no benefits.

  • 当网页上没有发生任何事情时,不会生成任何框架。

    ¥When nothing is happening on a webpage, no frames are generated.

  • 屏幕外窗口始终创建为 无框窗..

    ¥An offscreen window is always created as a Frameless Window..

渲染模式

¥Rendering Modes

GPU 加速

¥GPU accelerated

GPU 加速渲染是指使用 GPU 进行合成。因此,必须从 GPU 复制帧,这需要更多资源,因此该模式比软件输出设备慢。这种模式的好处是支持 WebGL 和 3D CSS 动画。

¥GPU accelerated rendering means that the GPU is used for composition. Because of that, the frame has to be copied from the GPU which requires more resources, thus this mode is slower than the Software output device. The benefit of this mode is that WebGL and 3D CSS animations are supported.

软件输出设备

¥Software output device

该模式使用软件输出设备在 CPU 中进行渲染,因此帧生成速度要快得多。因此,该模式优于 GPU 加速模式。

¥This mode uses a software output device for rendering in the CPU, so the frame generation is much faster. As a result, this mode is preferred over the GPU accelerated one.

要启用此模式,必须通过调用 app.disableHardwareAcceleration() API 禁用 GPU 加速。

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

示例

¥Example

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.