capture

mail@pastecode.io avatar
unknown
html
a year ago
2.0 kB
1
Indexable
Never
<html>
  <body>
    <button id="captureBtn">Capture</button>
    <canvas id="canvas" style="display: none;"></canvas>

    <script>
        const captureBtn = document.getElementById("captureBtn");
        const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext("2d");
        let mediaStream = null;

        async function startCapture() {
            const displayMediaOptions = {
                video: {
                    mediaSource: "screen",
                    displaySurface: "monitor",
                    logicalSurface: true,
                    cursor: "always"
                }
            };

            try {
                mediaStream = await navigator.mediaDevices.getDisplayMedia(
                    displayMediaOptions
                );

                const videoTrack = mediaStream.getVideoTracks()[0];
                const imageCapture = new ImageCapture(videoTrack);

                const bitmap = await imageCapture.grabFrame();
                canvas.width = bitmap.width;
                canvas.height = bitmap.height;

                ctx.drawImage(bitmap, 0, 0);

                canvas.toBlob((blob) => {
                    const url = URL.createObjectURL(blob);

                    const link = document.createElement("a");
                    link.download = "screenshot.png";
                    link.href = url;
                    link.click();

                    URL.revokeObjectURL(url);
                }, "image/png");
            } catch (err) {
                console.error("Error: " + err);
            } finally {
                stopCapture();
            }
        }

        function stopCapture() {
            if (mediaStream) {
            mediaStream.getTracks().forEach((track) => {
                track.stop();
            });
            }
        }

        captureBtn.addEventListener("click", () => {
            startCapture();
        });
    </script>
  </body>
</html>