Skip to content

Instantly share code, notes, and snippets.

@ezirmusitua
Last active January 17, 2019 15:53
Show Gist options
  • Save ezirmusitua/bfac6831c6374e8d25ae5ca50bf839b4 to your computer and use it in GitHub Desktop.
Save ezirmusitua/bfac6831c6374e8d25ae5ca50bf839b4 to your computer and use it in GitHub Desktop.
[Capture screenshot] implement capture screenshot in electron #electron #node
const fs = require('fs')
const os = require('os')
const path = require('path')
const electron = require('electron')
const desktopCapturer = electron.desktopCapturer
const electronScreen = electron.screen
const shell = electron.shell
const screenshot = document.getElementById('screen-shot')
const screenshotMsg = document.getElementById('screenshot-path')
function determineScreenShotSize () {
const screenSize = electronScreen.getPrimaryDisplay().workAreaSize
const maxDimension = Math.max(screenSize.width, screenSize.height)
return {
width: maxDimension * window.devicePixelRatio,
height: maxDimension * window.devicePixelRatio
}
}
screenshot.addEventListener('click', (event) => {
screenshotMsg.textContent = 'we are still working ...'
const thumbSize = determineScreenShotSize()
let options = {
types: ['screen'],
thumbnailSize: thumbSize
}
desktopCapturer.getSources(options, (error, sources) => {
if (error) return console.log(error)
sources.forEach((source) => {
// TODO: source.name is not determined
// use some other condition to decide use which screen(user may have multi screen) or full screen
if (source.name === 'Entire screen' || source.name === 'Screen 1') {
const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
fs.writeFile(screenshotPath, source.thumbnail.toPng(), (error) => {
if (error) return console.log(error)
shell.openExternal('file://' + screenshotPath)
const message = `Screenshot saved: ${screenshotPath}`
screenshotMsg.textContent = message
})
}
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment