📅  最后修改于: 2023-12-03 15:38:15.313000             🧑  作者: Mango
在 ElectronJS 中,截取屏幕截图可以通过 desktopCapturer
模块来实现。
desktopCapturer
模块可以访问屏幕和窗口捕获流,从而实现屏幕分享和录制等功能。在使用 desktopCapturer
模块之前,需要在 main
进程中引入该模块:
const { desktopCapturer } = require('electron')
截取屏幕截图的步骤如下:
desktopCapturer.getSources()
方法获取屏幕截图和窗口捕获流;完整代码如下:
// main.js
const { app, BrowserWindow, desktopCapturer } = require('electron')
let win
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.on('ready', createWindow)
// ipcMain 监听截屏事件
const { ipcMain } = require('electron')
ipcMain.on('capture-screen', async (event, arg) => {
// 获取屏幕截图和窗口捕获流
const sources = await desktopCapturer.getSources({ types: ['screen'] })
// 选择捕获源
const source = sources[0]
// 生成媒体流
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: source.id,
minWidth: 1280,
minHeight: 720,
maxWidth: 1280,
maxHeight: 720
}
}
})
// 将媒体流转为 Image 对象
const video = document.createElement('video')
video.srcObject = stream
video.play()
const canvas = document.createElement('canvas')
canvas.width = 1280
canvas.height = 720
const ctx = canvas.getContext('2d')
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
const dataUrl = canvas.toDataURL('image/png')
// 在渲染进程中显示 Image
event.reply('capture-screen-reply', dataUrl)
})
渲染进程中需要监听 capture-screen-reply
事件,并在回调函数中显示 Image,如下:
// index.js
const { ipcRenderer } = require('electron')
const captureScreenBtn = document.getElementById('capture-screen-btn')
captureScreenBtn.onclick = () => {
ipcRenderer.send('capture-screen')
}
ipcRenderer.on('capture-screen-reply', (event, arg) => {
const screenshotImg = document.getElementById('screenshot-img')
screenshotImg.src = arg
})