Trying to convert an SVG to PNG Image

1.4k views Asked by At

I have been dealing with this for a bit but I can't seem to get it to work. Onclick to resulting png image is empty. See the code below....

function svgToCanvas (targetElem,fileName) { 
    var nodesToRecover = [];
    var nodesToRemove = [];

    var svgElem = targetElem.find('svg');

    console.log(svgElem);

    svgElem.each(function(index, node) {
        var parentNode = node.parentNode;
        var svg = parentNode.innerHTML;

        var canvas = document.createElement('canvas');

        canvg(canvas, svg);

        nodesToRecover.push({
            parent: parentNode,
            child: node
        });

        parentNode.removeChild(node);

        nodesToRemove.push({
            parent: parentNode,
            child: canvas
        });

        parentNode.appendChild(canvas);
    });

    html2canvas(targetElem, {
        allowTaint: true,
        onrendered: function(canvas) {

            var theName = fileName + ".png";
            prev_img = theName;

            var a = document.createElement('a');
            a.href = canvas.toDataURL();
            a.download = theName;
            a.click();

        }

    }); 

}

#Running the function..
var theDiv = $('#divContainingSVG');
var fileNm = "imageName";
svgToCanvas(theDiv, fileNm);

Not sure where to go next. I simply need to convert the image to a png and then save it to the server. When testing the download version the resulting png is blank. Note that I'm using... canvg.js (including rgbcolor.js) and html2canvas.svg.js

Thanks in advance!

1

There are 1 answers

0
Ethan-Anthony On

Actually it turns out that this function works fine. The issue was a conflict with another function that was included, by mistake, to get the svg.