Electron 中实现滚动截图功能,可以分为几个步骤:
- 捕获网页内容:使用 Electron 提供的
webContents.capturePage()
方法可以捕获当前渲染进程的内容。这个方法会返回一个包含屏幕截图的NativeImage
对象。 - 模拟滚动:为了实现滚动截图,你需要在一个循环中不断地滚动网页内容,并使用
capturePage()
方法捕获每一帧。这可以通过调用webContents.executeJavaScript()
方法来执行 JavaScript 代码,实现滚动效果。 - 合并图片:将捕获的每帧图片合并成一个完整的长图。可以使用像
sharp
这样的库来处理图片的裁剪和合并。
下面是一个简化的示例代码,展示了如何实现滚动截图:
const { BrowserWindow } = require('electron');
const sharp = require('sharp');
const fs = require('fs');
async function captureScrollingScreen(win, targetUrl, outputFilename) {
const captureOptions = { x: 0, y: 0, width: win.getBounds().width, height: win.getBounds().height };
let images = [];
const nativeImage = await win.webContents.capturePage(captureOptions);
images.push(nativeImage);
const scrollHeight = await win.webContents.executeJavaScript(`
document.body.scrollHeight; // 获取页面总高度
`);
for (let offset = win.getBounds().height; offset < scrollHeight; offset += win.getBounds().height) {
// 滚动到指定位置
await win.webContents.executeJavaScript(`window.scrollTo(0, ${offset});`, true);
// 等待页面滚动渲染完成
await new Promise(resolve => setTimeout(resolve, 100));
const image = await win.webContents.capturePage(captureOptions);
images.push(image);
}
// 合并图片
const mergedImage = await sharp({
create: {
width: win.getBounds().width,
height: scrollHeight,
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 1 }
}
});
for (const image of images) {
await mergedImage.append(image.resize({ width: win.getBounds().width }));
}
// 保存图片到文件
await mergedImage.toFile(outputFilename);
}
// 使用方法
const mainWindow = new BrowserWindow();
mainWindow.loadURL('file://' + __dirname + '/index.html'); // 加载本地文件
mainWindow.once('ready-to-show', async () => {
await captureScrollingScreen(mainWindow, 'file://' + __dirname + '/index.html', 'output.png');
});
在上述代码中,我们创建了一个名为 captureScrollingScreen
的函数,该函数接收一个 BrowserWindow 实例、目标URL和输出文件名作为参数。首先捕获当前窗口的截图,然后通过循环滚动页面,并在每次滚动后捕获新的截图。最后,使用 sharp
库将所有截图合并成一个长图