Created
November 27, 2019 08:40
-
-
Save bytemain/b8e0ba8ab82160b3523943111f181e4b to your computer and use it in GitHub Desktop.
Take screen shots of window or desktop with js https://codepen.io/designalchemy/pen/WNNmOgP?editors=1010
This file contains 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
<button id="cake">Take Screeny</button> | |
<br /> | |
<canvas id="fake"></canvas> |
This file contains 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
const canIRun = navigator.mediaDevices.getDisplayMedia | |
const takeScreenShot = async () => { | |
const stream = await navigator.mediaDevices.getDisplayMedia({ | |
video: { mediaSource: 'screen' }, | |
}) | |
// get correct video track | |
const track = stream.getVideoTracks()[0] | |
// init Image Capture and not Video stream | |
const imageCapture = new ImageCapture(track) | |
// take first frame only | |
const bitmap = await imageCapture.grabFrame() | |
// destory video track to prevent more recording / mem leak | |
track.stop() | |
const canvas = document.getElementById('fake') | |
// this could be a document.createElement('canvas') if you want | |
// draw weird image type to canvas so we can get a useful image | |
canvas.width = bitmap.width | |
canvas.height = bitmap.height | |
const context = canvas.getContext('2d') | |
context.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height) | |
const image = canvas.toDataURL() | |
// this turns the base 64 string to a [File] object | |
const res = await fetch(image) | |
const buff = await res.arrayBuffer() | |
// clone so we can rename, and put into array for easy proccessing | |
const file = [ | |
new File([buff], `photo_${new Date()}.jpg`, { | |
type: 'image/jpeg', | |
}), | |
] | |
return file | |
} | |
const button = document.getElementById('cake').onclick = () => canIRun ? takeScreenShot() : {} |
Works in Brave (Chrome) but not in Firefox. Firefox do not have support for ImageCapture
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working on chrome