使用Electron选择桌面屏幕区域

时间:2017-02-28 22:29:08

标签: node.js electron

我正在尝试编写一个允许用户选择屏幕区域的应用程序(比如选择拍摄屏幕)。

folders in home

这甚至可能吗?

2 个答案:

答案 0 :(得分:2)

我怀疑您仍在寻找解决方案,但是在挖掘之后,我找到了一种结合使用shelljs和剪贴板的方法。

error

答案 1 :(得分:1)

要专门拍摄全屏,请使用以下代码(从Electron Demo App中提取示例)。您可以构建此示例,并使用电子API中的screendesktopCapturerrectangle模块来自定义代码以获取特定的屏幕/显示,或选择特定的边界框(x / y坐标和像素区域)。

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 = 'Gathering screens...'
  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 = `Saved screenshot to: ${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
  }
}

你可以采取的其他方式是:

  1. 在DOM中使用object.getClientRects()指定要捕获的特定元素,但这需要预知它们是什么。
  2. 在视图中添加事件监听器,以使用mouseClick,mouseMove等“绘制”您想要的形状。这个stack overflow question的答案可以根据您的需要进行调整。