此係列文章的應用示例已發佈於 GitHub: electron-api-demos-Zh_CN. 能夠 Clone 或下載後運行查看. 歡迎 Star .git
Electron 中的 desktopCapturer
模塊可用於訪問 Chromium 的 getUserMedia
web API 中提供的任何媒體, 例如音頻, 視頻, 屏幕和窗口.github
這個模塊有一個版本可用於這兩個進程: ipcMain
和 ipcRenderer
.web
在瀏覽器中查看 完整 API 文檔.shell
支持: Win, macOS, Linux | 進程: 渲染器api
此示例使用 desktopCapturer
模塊採集正在使用的屏幕, 並建立全屏幕截圖.瀏覽器
點擊示例按鈕將截取當前屏幕的截圖, 並在默認查看器中打開它.electron
渲染器進程ui
const electron = require('electron') const desktopCapturer = electron.desktopCapturer const electronScreen = electron.screen const shell = electron.shell const fs = require('fs') const os = require('os') const path = require('path') const screenshot = document.getElementById('screen-shot') const screenshotMsg = document.getElementById('screenshot-path') screenshot.addEventListener('click', function (event) { screenshotMsg.textContent = '正在採集屏幕...' const thumbSize = determineScreenShotSize() let options = { types: ['screen'], thumbnailSize: thumbSize } desktopCapturer.getSources(options, function (error, sources) { if (error) return console.log(error) sources.forEach(function (source) { if (source.name === 'Entire screen' || source.name === 'Screen 1') { const screenshotPath = path.join(os.tmpdir(), 'screenshot.png') fs.writeFile(screenshotPath, source.thumbnail.toPng(), function (error) { if (error) return console.log(error) shell.openExternal('file://' + screenshotPath) const message = `截圖保存到: ${screenshotPath}` screenshotMsg.textContent = message }) } }) }) }) function determineScreenShotSize () { const screenSize = electronScreen.getPrimaryDisplay().workAreaSize const maxDimension = Math.max(screenSize.width, screenSize.height) return { width: maxDimension * window.devicePixelRatio, height: maxDimension * window.devicePixelRatio } }
若是這邊文章對您有幫助, 感謝 下方點贊 或 Star GitHub: electron-api-demos-Zh_CN 支持, 謝謝.spa