Last active
March 31, 2021 10:41
-
-
Save QuarkGluonPlasma/dcdb7a6095ad4bafc7f323c2be140e62 to your computer and use it in GitHub Desktop.
获取electron窗口截图,转成base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { desktopCapturer } from 'electron'; | |
let video: HTMLVideoElement; | |
/** | |
* 获取窗口截图,转成base64 | |
* @param document | |
*/ | |
export default function getScreenshotData(document: Document) { | |
return new Promise(async (resolve, reject) => { | |
const captureSources = await desktopCapturer.getSources({ types: ['window']}); | |
const targetCaptureSource = captureSources.filter(item => item.name === document.title)[0]; | |
if (targetCaptureSource) { | |
try { | |
const mediaStream = await navigator.mediaDevices.getUserMedia({ | |
audio: false, | |
video: { | |
mandatory: { | |
chromeMediaSource: 'desktop', | |
chromeMediaSourceId: targetCaptureSource.id, | |
maxWidth: document.body.clientWidth, | |
maxHeight: document.body.clientHeight, | |
minWidth: document.body.clientWidth, | |
minHeight: document.body.clientHeight | |
} | |
} | |
} as MediaStreamConstraints); | |
{ | |
if(!video) { | |
video = document.createElement('video'); | |
} | |
video.srcObject = mediaStream; | |
video.onloadedmetadata = () => { | |
video.play(); | |
let canvas = document.createElement('canvas'); | |
canvas.width = document.body.clientWidth; | |
canvas.height = document.body.clientHeight; | |
const ctx = canvas.getContext('2d'); | |
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); | |
video.pause(); | |
resolve(canvas.toDataURL('image/jpeg')); | |
} | |
} | |
} catch(e) { | |
reject(e); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment