Skip to content

js screenshot

javascript
const sleep = (time) => new Promise(resolve => setTimeout(resolve, time));

const loadHtml2CanvasScript = async () => {
    return new Promise(resolve => {
        const scriptTag = document.createElement('script');
        scriptTag.src = 'https://html2canvas.hertzen.com/dist/html2canvas.min.js';
        scriptTag.onload = resolve;
        document.head.appendChild(scriptTag);
    });
};

const captureScreenshot = async () => {
    await loadHtml2CanvasScript();

    while (typeof html2canvas === 'undefined') {
        await sleep(500);
    }

    const canvas = document.createElement('canvas');
    canvas.width = window.outerWidth;
    canvas.height = window.outerHeight;

    const context = canvas.getContext('2d');
    const htmlElement = document.documentElement;

    context.drawImage(
        await html2canvas(htmlElement),
        0, 0,
        canvas.width, canvas.height,
        0, 0,
        window.outerWidth, window.outerHeight
    );

    return canvas.toDataURL('image/png');
};

const main = async () => {
    await sleep(1000);
    console.log(await captureScreenshot());
};

main();

Released under the MIT License.