截屏元素并将其保存为Electron中的图像

时间:2018-06-18 23:57:11

标签: javascript html image npm electron

我正在尝试截取我的应用程序的一部分,然后将屏幕截图保存为图像。但屏幕截图(<img>和文件)仅显示窗口的框架,图像的其余部分为黑色。我的电子版是:2.0.2

function appScreenshot() {
    function handleStream(stream) {
        var video = document.createElement("video");
        video.onloadedmetadata = function () {
            video.style.height = this.videoHeight + "px";
            video.style.width = this.videoWidth + "px";
            var canvas = document.createElement("canvas");
            canvas.width = this.videoWidth;
            canvas.height = this.videoHeight;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

            var base64 = canvas.toDataURL("image/jpeg");

            document.querySelector("img").setAttribute("src", canvas.toDataURL("image/jpeg"));
            var base64Data = base64.replace(/^data:image\/jpeg;base64,/, "");

            fs.writeFileSync("test.jpg", base64Data, "base64");

            video.remove();
            try { stream.getTracks()[0].stop(); } catch (err) { }
        };
        video.src = URL.createObjectURL(stream);
        document.body.appendChild(video);
    }

    function handleError() { }

    desktopCapturer.getSources({ types: ["window"] }, (error, sources) => {
        for (let source of sources) {
            if (source.name === "myapp") {
                navigator.webkitGetUserMedia({
                    audio: false,
                    video: {
                        mandatory: {
                            chromeMediaSource: "desktop",
                            chromeMediaSourceId: source.id,
                            minWidth: 1280,
                            maxWidth: 4000,
                            minHeight: 720,
                            maxHeight: 4000
                        }
                    }
                }, handleStream, handleError);
                return;
            }
        }
    });
}

0 个答案:

没有答案
相关问题