3

我正在使用 navigator.mediaDevices.getDisplayMedia 来获取屏幕截图,但它捕获了页面的唯一可见部分,但还有更多内容隐藏在滚动区域中并且被遗漏了。那么是否有可能捕获整页?

   function getDisplayMedia(options) {
        if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
            return navigator.mediaDevices.getDisplayMedia(options)
        }
        if (navigator.getDisplayMedia) {
            return navigator.getDisplayMedia(options)
        }
        if (navigator.webkitGetDisplayMedia) {
            return navigator.webkitGetDisplayMedia(options)
        }
        if (navigator.mozGetDisplayMedia) {
            return navigator.mozGetDisplayMedia(options)
        }
        throw new Error('getDisplayMedia is not defined')
    }

    async function takeScreenshotStream() {
        const width = screen.width * (window.devicePixelRatio || 1)
        const height = screen.height * (window.devicePixelRatio || 1)

        const errors = [];
        let stream;
        const mediaStreamConstraints = {
            audio: false,
            video: {
                width,
                height,
                frameRate: 1,
            },
        };

        try {
            stream = await getDisplayMedia(mediaStreamConstraints)
        } catch (ex) {
            errors.push(ex)
        }

        if (errors.length) {
            console.debug(...errors)
            if (!stream) {
                throw errors[errors.length - 1]
            }
        }

        return stream
    }

    async function takeScreenshotCanvas() {
        const stream = await takeScreenshotStream()
        const video = document.createElement('video')
        const result = await new Promise((resolve, reject) => {
            video.onloadedmetadata = () => {
                video.play()
                video.pause()
                const canvas = document.createElement('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                const context = canvas.getContext('2d')
                context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
                resolve(canvas)
            }
            video.srcObject = stream
        })

        stream.getTracks().forEach(function (track) {
            track.stop()
        })

        if (result == null) {
            throw new Error('Cannot take canvas screenshot')
        }

        return result
    }

    document.body.onclick = async () => {
        const canvas = await takeScreenshotCanvas()
        document.getElementById("screenshot-preview").src = canvas.toDataURL(); 
    }

我尝试使用 Html2Canvas 和 dom-to-image 来截取整页截图,但它们有自己的回退,就像他们不捕获 iframe、SVG 等一样。

任何帮助将不胜感激。

4

0 回答 0