Offscreen Rendering屏幕外渲染
Overview概述
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. BrowserWindow
的内容,因此可以在任何位置进行渲染,例如在3D场景中的纹理上。The offscreen rendering in Electron uses a similar approach to that of the Chromium Embedded Framework project.Electron中的屏幕外渲染使用与Chromium嵌入式框架项目类似的方法。
Notes:
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.paint
事件以提高效率。You can stop/continue the rendering as well as set the frame rate.可以停止/继续渲染并设置帧速率。The maximum frame rate is 240 because greater values bring only performance losses with no benefits.最大帧速率为240,因为更大的值只会带来性能损失,而不会带来任何好处。When nothing is happening on a webpage, no frames are generated.当网页上没有发生任何事情时,不会生成任何框架。An offscreen window is always created as a Frameless Window..屏幕外窗口始终创建为无框架窗口。
Rendering Modes渲染模式
GPU acceleratedGPU加速
GPU accelerated rendering means that the GPU is used for composition. GPU加速渲染意味着GPU用于合成。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. 因此,必须从需要更多资源的GPU复制帧,因此这种模式比软件输出设备慢。The benefit of this mode is that WebGL and 3D CSS animations are supported.此模式的好处是支持WebGL和3D CSS动画。
Software output device软件输出设备
This mode uses a software output device for rendering in the CPU, so the frame generation is much faster. 该模式使用软件输出设备在CPU中进行渲染,因此帧生成速度更快。As a result, this mode is preferred over the GPU accelerated one.因此,该模式优于GPU加速模式。
To enable this mode, GPU acceleration has to be disabled by calling the app.disableHardwareAcceleration() API.要启用此模式,必须通过调用app.disableHardwareAcceleration()API禁用GPU加速。
Example示例
- main.js
const { app, BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
app.disableHardwareAcceleration()
let win
app.whenReady().then(() => {
win = new BrowserWindow({ 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.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
After launching the Electron application, navigate to your application's working folder, where you'll find the rendered image.启动Electron应用程序后,导航到应用程序的工作文件夹,在那里可以找到渲染图像。