Upload an image from a canva javascript to an SVG

112 Views Asked by At

Here's the beginning of my codeI made some plots in a javascript canvas and I would like to be able to download them in svg format directly to my computer's hard drive. So I made a button, and a function in javascript, however I must have made a mistake, because when I click nothing happens.

I've test with a javascript function:

        function downloadSVG() {
        var canvas = document.getElementById("mon-canvas");
        var svg = document.createElement("div");
        svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        svg.setAttribute("width", canvas.width);
        svg.setAttribute("height", canvas.height);

        var dessin = document.getElementById("mon-dessin").innerHTML;
        svg.innerHTML = '<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">' +
            dessin +
            '</div></foreignObject>';

        canvg(canvas, svg.innerHTML, {
            ignoreMouse: true,
            ignoreAnimation: true,
            ignoreDimensions: true,
            scaleWidth: canvas.width,
            scaleHeight: canvas.height,
            renderCallback: function() {
                var link = document.createElement("a");
                link.download = "mon-dessin.svg";
                link.href = "data:image/svg+xml;base64," + btoa(svg.innerHTML);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
        });
    }

</script> 

<button id="telechargerSVG" onclick="downloadSVG()">Télécharger en SVG</button>
1

There are 1 best solutions below

0
temp-poster On

Miscellaneous observations:

1. Attributes only accept strings so...

svg.setAttribute("width", canvas.width.toString());

2. Good luck with...

<foreignObject>

I've never been able to get that to work with anything serious.

3. Totally unnecessary, you don't need these:

document.body.appendChild(link);

document.body.removeChild(link);

4. I would change...

link.href = "data:image/svg+xml;base64,"+btoa(svg.innerHTML);

To this...

link.href = 'data:image/svg+xml;base64,'+btoa(unescape(encodeURIComponent(svg.innerHTML)));

Good luck with everything.