Friday, 29 July 2016

Take a screenshot of whole app in the Electron

First you need to enable usermedia-screen-capturing in your Chromium Electron,
add the following string into your main.js:
app.commandLine.appendSwitch('enable-usermedia-screen-capturing');

After that you can use the following function to take a PNG blob
/**
 * A simplified function which takes a screenshot with webkitGetUserMedia
 * and returns this screenshot as a PNG blob into the callback
 * @param callback (pngData: Blob) => void
 * @returns void
 */
function takeScreenShot (callback) {
    let screenConstraints = {
        mandatory: {
            chromeMediaSource: "screen",
            maxHeight: 1080,
            maxWidth: 1920,
            minAspectRatio: 1.77
        },
        optional: []
    };

    let session = {
        audio: false,
        video: screenConstraints
    };

    let streaming = false;
    let canvas = document.createElement("canvas");
    let video = document.createElement("video");
    document.body.appendChild(canvas);
    document.body.appendChild(video);
    let width = screen.width;
    let height = 0;

    video.addEventListener("canplay", function(){
        if (!streaming) {
            height = video.videoHeight / (video.videoWidth / width);

            if (isNaN(height)) {
                height = width / (4 / 3);
            }

            video.setAttribute("width", width.toString());
            video.setAttribute("height", height.toString());
            canvas.setAttribute("width", width.toString());
            canvas.setAttribute("height", height.toString());
            streaming = true;

            let context = canvas.getContext("2d");
            if (width && height) {
                canvas.width = width;
                canvas.height = height;
                context.drawImage(video, 0, 0, width, height);

                canvas.toBlob(function (data) {
                    video.pause();
                    video.src = "";
                    document.body.removeChild(video);
                    document.body.removeChild(canvas);
                    callback(data); // here the png blob returned to the callback
                });
            }
        }
    }, false);

    navigator.webkitGetUserMedia(session, function (stream) {
        video.src = window.webkitURL.createObjectURL(stream);
        video.play();
    }, function () {
        console.error("Can't take a screenshot");
    });
}