Convert SVG to image (JPEG, PNG, etc.) in the browser

前端 未结 9 1066
春和景丽
春和景丽 2020-11-21 23:38

I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.

9条回答
  •  青春惊慌失措
    2020-11-22 00:11

    Here a function that works without libraries and returns a Promise:

    /**
     * converts a base64 encoded data url SVG image to a PNG image
     * @param originalBase64 data url of svg image
     * @param width target width in pixel of PNG image
     * @return {Promise} resolves to png data url of the image
     */
    function base64SvgToBase64Png (originalBase64, width) {
        return new Promise(resolve => {
            let img = document.createElement('img');
            img.onload = function () {
                document.body.appendChild(img);
                let canvas = document.createElement("canvas");
                let ratio = (img.clientWidth / img.clientHeight) || 1;
                document.body.removeChild(img);
                canvas.width = width;
                canvas.height = width / ratio;
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                try {
                    let data = canvas.toDataURL('image/png');
                    resolve(data);
                } catch (e) {
                    resolve(null);
                }
            };
            img.src = originalBase64;
        });
    }
    

    On Firefox there is an issue for SVGs without set width / height.

    See this working example including a fix for the Firefox issue.

提交回复
热议问题