electron 实现截图功能

实现方式:引入第三方exe,然后调用。

 

创建一个新的electron项目,把下方代码复制带main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const {globalShortcut} = require('electron');
const {execFile} = require('child_process');
const isDevelopment = process.env.NODE_ENV !== "production";
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
  globalShortcut.register('CommandOrControl+Alt+h', function () {
    console.log('111111111111111111111')
    screenWindow();

  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow()
})
// 快捷键模块


//
// // 加载子进程
//

//
// // 截图方法
//
let screenWindow = () => {
  console.log('__dirname', __dirname)
  let url = path.resolve(__dirname, "../extraResources/PrintScr.exe");
  if (isDevelopment && !process.env.IS_TEST) {
    // 生产环境
    let url = path.join(__dirname, '/qq/PrintScr.exe');
  }

  let screen_window = execFile(url);
  // console.log(screen_window)
  screen_window.on('exit', (code) => {
    console.log('jinlaile')
    mainWindow.restore();
    if (code) console.log(code)
  })
}
// // 添加快捷键

//    globalShortcut.register('CommandOrControl+Alt+L', function () {
//     screenWindow();
//
// });


// 退出electron的时候一定要删除快捷键

//globalShortcut.unregisterAll()
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

调用的exe路径

已上可以实现生产环境截图了。


大坑:打包后截图不行,猜测可能是打包后文件损坏。后百度到在package.json文件里面build脚本内加入以下代码:

 extraResources: [
          {
            from: "./qq/PrintScr.exe", // 文件源路径
            to: "./extraResources/PrintScr.exe" // 打包后要放的路径
          },
          {
            from: "./qq/PrScrn.dll",
            to: "./extraResources/PrScrn.dll"
          }
        ]

打包后exe文件在     项目安装地址\resources\extraResources

调用第三方实现截图 转载 https://www.jianshu.com/p/77a3f0fadcf1

配置  转载 https://blog.csdn.net/PLF_1994/article/details/88301660

已上就可以实现截图了

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在 Electron Vue3 项目中实现截图功能,可以使用 Electron 的 desktopCapturer API 获取屏幕截图,然后使用 Canvas API 将截图渲染到画布上,最后将画布转换成图像文件保存。 以下是一个简单的实现示例: 1. 引入必要的模块和库: ``` const { desktopCapturer } = require('electron') const { createCanvas, loadImage } = require('canvas') const fs = require('fs') ``` 2. 创建一个函数来获取屏幕截图: ``` async function captureScreen() { const sources = await desktopCapturer.getSources({ types: ['screen'] }) const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sources[0].id, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }) const video = document.createElement('video') video.srcObject = stream video.play() const canvas = createCanvas(video.videoWidth, video.videoHeight) const ctx = canvas.getContext('2d') video.addEventListener('loadedmetadata', () => { canvas.width = video.videoWidth canvas.height = video.videoHeight }) video.addEventListener('play', () => { const draw = () => { ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight) requestAnimationFrame(draw) } requestAnimationFrame(draw) }) return canvas.toDataURL('image/png') } ``` 3. 创建一个按钮来触发截图操作: ``` <template> <div> <button @click="capture()">Capture</button> </div> </template> <script> const { desktopCapturer } = require('electron') const { createCanvas, loadImage } = require('canvas') const fs = require('fs') export default { methods: { async capture() { const dataURL = await captureScreen() const buffer = Buffer.from(dataURL.split(',')[1], 'base64') fs.writeFileSync('./screenshot.png', buffer) } } } </script> ``` 这样,当用户点击按钮时,将会在项目根目录下生成一个名为 `screenshot.png` 的截图文件。 注意,由于 Electron 中使用了 Node.js 的文件系统 API,因此需要在 `main.js` 文件中设置 `nodeIntegration: true` 才能正常运行此功能
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值