【问题标题】:How to take screenshot using electronjs?如何使用electronjs截屏?
【发布时间】:2021-02-27 03:52:49
【问题描述】:

我正在构建一个跨平台的桌面应用程序。我正在使用 electronjs 框架进行桌面应用程序开发。我想添加一个功能,在我的应用程序启动时每 5 分钟截屏一次!

我们将不胜感激 我的 main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow,Tray,Menu} = require('electron')
const path = require('path')
const iconz = path.join(__dirname,'/img/download.png')
const fs = require('fs')
var config = require('./login.json');
const shell = require('electron').shell



let tray = null



function createWindow () {

  tray = new Tray(iconz)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'User:'+ config.username, type: 'radio',enabled:false},
    {type:'separator'},
    { label: 'Show DeskTime', type: 'radio',
    click() { 
      shell.openExternal('http://coinmarketcap.com')
      } 
    },
    {type:'separator'},
    { label: 'Private Time', type: 'radio',
    click() { 
      checked:true
      } 
    },
    {type:'separator'},
    { label: 'LogOut', type: 'radio' },
    {type:'separator'},
    { label: 'Quit', type: 'radio',
      click() { 
          app.quit() 
      }
    }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)



  console.log(config.username + ' ' + config.password);
  if(config.username == ""){

   // Create the browser window.
  const 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()
}

// 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.whenReady().then(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 (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// 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.

我的 index.html

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}

input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}

button:hover {
  opacity: 0.8;
}

.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

.imgcontainer {
  text-align: center;
  margin: 12px 0 6px 0;
}

img.avatar {
  width: 20%;
  border-radius: 40%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
</style>
</head>
<body>

<h2>Login Form</h2>

<form action="/action_page.php" method="post">
  <div class="imgcontainer">
    <img src="login_logo.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label for="uname"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="uname" required>

    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit">Login</button>
    <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>

  </div>

  <div class="container" style="background-color:#f1f1f1">


    <span class="psw">Forgot <a href="#">password?</a></span>
  </div>
</form>
<label id="screenshot-path">Path:</label>
<button  id="screen-shot" type="button" class="cancelbtn">Singup</button>
</body>

   <script src="./renderer.js"></script>


</html>




上面给出了我的代码,请通过这个并帮助我在一定间隔内截屏。以及如何将屏幕截图保存在预定义的文件夹中。

【问题讨论】:

    标签: electron electron-packager


    【解决方案1】:

    您可以在主进程中使用contents.capturePage([rect])。如果您省略 rect args 它将捕获整个窗口。这将返回一个带有 native image 的承诺。

    1. 要每 5 分钟捕获一次,您可以设置 setInterval(&lt;function&gt;,&lt;time in millis&gt;)
    2. 要保存在特定文件夹中,您可以使用path 模块

    例如:

    const path = require('path')
    const myFolderPath = path.join(__dirname, "myfolderinsideProject")
    fs.writeFile(path.join(myFolderPath,`test${count}.png`), ....)
    

    将捕获的窗口保存到当前项目文件夹的示例代码:

    // Modules to control application life and create native browser window
    const {app, BrowserWindow } = require('electron')
    const path = require('path')
    const fs = require('fs')
    let mainWindow, count=0;
    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()
    }
    
    // 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.whenReady().then(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 (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
    
    //starting when the app is ready
    app.on('ready', () => {
      //setting the time interval for 3 second (3000 in millis)
      setInterval(()=>{
        console.log(`Capturing Count: ${count}`)
        //start capturing the window
        mainWindow.webContents.capturePage().then(image => 
        {
          //writing  image to the disk
              fs.writeFile(`test${count}.png`, image.toPNG(), (err) => {
              if (err) throw err
              console.log('Image Saved')
              count++
              })
        })
        }, 3000); //tome in millis
      });
    

    或者你可以在渲染进程上使用这个npm package

    【讨论】:

      猜你喜欢
      • 2013-08-11
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多