Search code examples
javascriptscreenshotscreen-capture

How to take screen shot of entire client machine not only web browser or a web page from javascript


I want to capture the screenshot to a image not the video. I found ways to do that but they are either capturing the current web page or recoding the video from entire screen. I found This library to record screen. This is doing something similar which WebRTC does. My requirement is to just take an image of entire screen programmatically from my web application written in plain javascript. Is there any way I can do it ? Thanks


Solution

  • From the MediaStream you get through the Media Capture and Streams API, you can create an ImageCapture instance and call its grabFrame() method that will produce an ImageBitmap you'll be able to paint on a <canvas>.

    const stream = await navigator.mediaDevices.getDisplayMedia();
    const track = stream.getVideoTracks()[0];
    const capture = new ImageCapture(track);
    // when you need the still image
    const bitmap = await capture.grabFrame();
    // if you want a Blob version
    const canvas = document.createElement("canvas");
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext("bitmaprenderer").transferFromImageBitmap(bitmap);
    const blob = await new Promise((res) => canvas.toBlob(res));
    

    Now, I should note that this ideal path is currently only accessible to Chromium based browsers.
    For other browsers you'd need to set the srcObject of an HTMLVideoElement to the MediaStream, and to drawImage that HTMLVideoElement on a 2D context.