Created
March 28, 2023 20:28
-
-
Save BoQsc/be2034af19b0d10da3d037ddf5f4e878 to your computer and use it in GitHub Desktop.
Screenshot example in javascript clientside
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Screenshot Demo</title> | |
<style> | |
#v, | |
#i { | |
width: 1920px; | |
height: 1080px; | |
} | |
#v { | |
border: 1px solid blue; | |
} | |
#i { | |
border: 1px solid green; | |
} | |
</style> | |
</head> | |
<body> | |
<div> | |
<video style="opacity: 0; position: fixed; z-index: -9999;" id="v" autoplay></video> | |
<button id="b">Take screenshot</button> | |
<img style="display: none;" id="i" src="//:0" /> | |
</div> | |
<script> | |
const v = document.getElementById("v"); | |
const b = document.getElementById("b"); | |
const i = document.getElementById("i"); | |
b.onclick = async () => { | |
try { | |
b.innerText = 'Waiting for Recording approval'; | |
b.style.opacity = 0; | |
const stream = await navigator.mediaDevices.getDisplayMedia({ | |
audio: false, | |
video: true, | |
preferCurrentTab: true | |
}); | |
v.srcObject = stream; | |
await new Promise(resolve => { | |
v.addEventListener('loadedmetadata', resolve); | |
}); | |
b.style.opacity = 1; | |
b.innerText = 'Taking a screenshot'; | |
// take screenshot | |
const scale = 1; | |
const canvas = document.createElement("canvas"); | |
canvas.width = v.videoWidth * scale; | |
canvas.height = v.videoHeight * scale; | |
canvas.getContext('2d').drawImage(v, 0, 0, canvas.width, canvas.height); | |
b.style.opacity = 1; | |
b.innerText = 'Waiting for clipboard popup'; | |
const blob = await new Promise((resolve) => { | |
canvas.toBlob(resolve, 'image/png'); | |
}); | |
// write to clipboard | |
await navigator.clipboard.write([ | |
new ClipboardItem({ 'image/png': blob }) | |
]); | |
console.log('Screenshot copied to clipboard'); | |
b.innerText = 'Screenshot saved to clipboard'; | |
// stop video | |
const tracks = v.srcObject.getTracks(); | |
tracks.forEach(track => track.stop()); | |
v.srcObject = null; | |
// display the screenshot | |
i.src = URL.createObjectURL(blob); | |
} catch (err) { | |
console.error('Failed to take screenshot:', err); | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment