Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created February 27, 2025 18:10
Show Gist options
  • Save Garciat/2cf5ff2aae4d7226a47f61101faa96cb to your computer and use it in GitHub Desktop.
Save Garciat/2cf5ff2aae4d7226a47f61101faa96cb to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Screen Capture</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="container" style="border: 3px solid red; display: inline-block">
<h1>Screen Capture</h1>
<p>Click the button to capture this box.</p>
<button onclick="capture()">Capture</button>
</div>
<div id="message"></div>
<div id="timer"></div>
<script>
const unsupported = [];
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
unsupported.push("Screen Capture API");
}
if (!window.ImageCapture) {
unsupported.push("ImageCapture");
}
if (!window.OffscreenCanvas) {
unsupported.push("OffscreenCanvas");
}
if (!window.CropTarget) {
unsupported.push("CropTarget");
}
if (unsupported.length) {
document.getElementById("message").innerText =
`This browser does not support the followring required features: ${unsupported.join(", ")}`;
}
async function capture() {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
preferCurrentTab: true,
});
const [track] = stream.getVideoTracks();
try {
const mainContentArea = document.getElementById("container");
const cropTarget = await CropTarget.fromElement(mainContentArea);
await track.cropTo(cropTarget);
for (let i = 3; i >= 0; i--) {
document.getElementById("timer").innerText = i;
await sleep(1000);
}
const imageCapture = new ImageCapture(track);
const bitmap = await imageCapture.grabFrame();
const { width, height } = bitmap;
const canvas = new OffscreenCanvas(width, height);
canvas.getContext("bitmaprenderer").transferFromImageBitmap(bitmap);
const blob = await canvas.convertToBlob();
const url = URL.createObjectURL(blob);
const img = document.createElement("img");
img.src = url;
img.width = width / window.devicePixelRatio;
img.height = height / window.devicePixelRatio;
document.body.appendChild(img);
} catch (error) {
console.error(error);
} finally {
track.stop();
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment