tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.38k stars 1.69k forks source link

Added toWebp method #164

Open meefik opened 7 years ago

meefik commented 7 years ago

Added saving to WebP format

tsayen commented 6 years ago

Frankly that's the first time I hear about WebP :) Would be OK to merge if Firefox supported this format, it still seems like it doesn't, also a regression test would be cool

bilelz commented 1 year ago

While waiting for the merge, I use this

async function screenshot() {
        return new Promise(async (resolve, reject) => {
             const el = document.getElementById("screenshot");
            domtoimage
                .toBlob(el)
                .then(async function (blob) {
                    const img = document.createElement("img");
                    img.src = URL.createObjectURL(blob);

                    // convert to .webp or .jpeg image
                    img.onload = async function () {
                        const canvas = document.createElement("canvas");
                        canvas.width = img.width;
                        canvas.height = img.height;
                        const ctx = canvas.getContext("2d");
                        ctx.drawImage(img, 0, 0);

                        const webP = new Image();
                        webP.src =
                            "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
                        webP.onload = webP.onerror = () => {
                            const supportWebp = webP.height === 2;
                            const imageType = supportWebp ? "image/webp" : "image/jpeg"; //prettier-ignore
                            const imageExtension = supportWebp ? "webp" : "jpeg"; //prettier-ignore

                            canvas.toBlob((blob) => {
                                const file = new File(
                                    [blob],
                                    `MyScreenshot.${imageExtension}`, //prettier-ignore
                                    { type: imageType }
                                );
                                resolve(file);
                            }, imageType);
                        };
                    };
                })
                .catch(function (error) {
                    console.error("domtoimage", error);
                    reject(error);
                })
                .finally(function () {
                   //...
                });
        });