简体   繁体   中英

Export SVG D3 js to PNG or JPEG and send by email

I have a javascript code that exports a svg d3 to a png or jpg image. When the svg is exported it sends an email (to send the email I use smtpjs) with the image, the image is downloaded perfectly but when I open it, it loses quality and almost all the graphics are erased, and the image that reaches the email comes empty. Is there a way to fix this?

**CODE: **

function svgString2Image(svgString, width, height, format, callback) {
        var format = format ? format : 'png';

        var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString)));// Convert SVG string to data URL

        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");

        canvas.width = width;
        canvas.height = height;

        var image = new Image();
        image.onload = function () {
            context.clearRect(0, 0, width, height);
            context.drawImage(image, 0, 0, width, height);

            canvas.toBlob(function (blob) {
                var filesize = Math.round(blob.length / 1024) + ' KB';
                if (callback) callback(blob, filesize);
            });
        };

        image.src = imgsrc;
        console.log(image.src)

        Email.send({
            SecureToken: "09f68b-d5e5-425-ba8-5d6b9419",
            To: 'em@gmail.com',
            From: "em@gmail.com",
            Subject: "This is the subject",
            Body: "iuwaehfiuwreu",
            Attachments: [
                {
                    name: "smtpjs.png",
                    data: canvas.toDataURL()
                    //data: imgsrc
                    //data: image.src
                }]
        }).then(
            message => alert(message)
        );
    }

I could repair it, modify some attributes of the context, which causes some parts of the graphic to be erased, what worked for me was to put the fillRect attribute blank and then draw the image. That worked for me.

** CODE: **

context.fillStyle = "white";
context.fillRect(0, 0, w, h);
context.drawImage(image, 0, 0, w, h);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM