dom-to-image icon indicating copy to clipboard operation
dom-to-image copied to clipboard

Added toWebp method

Open meefik opened this issue 7 years ago • 2 comments

Added saving to WebP format

meefik avatar Oct 30 '17 17:10 meefik

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

tsayen avatar Sep 19 '18 20:09 tsayen

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 () {
                   //...
                });
        }); 

bilelz avatar Mar 10 '23 13:03 bilelz