Search code examples
javascriptjquerysvgcanvg

Jquery: convert SVG to PNG with new size


I´m using the following function to transform an SVG into a PNG and offer it as a download:

<svg id="chart">
    ...some contenthere
</svg>

function() {
        var svg = $("#chart")[0],
            bBox = $('#chart')[0].getBBox();

        var width = bBox.width*2,
            height = bBox.height*2;

        var canvas = $("canvas")[0],
            serializer = new XMLSerializer(),
            svgString = serializer.serializeToString(svg);

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

        canvg(canvas, svgString);

        var dataURL = canvas.toDataURL('image/png'),
            data = atob(dataURL.substring('data:image/png;base64,'.length));

        asArray = new Uint8Array(data.length);

        for (var i = 0; i < data.length; ++i) {
            asArray[i] = data.charCodeAt(i); 
            } 

        var blob = new Blob([asArray.buffer], {type: 'image/png'}); 
        saveAs(blob, 'climatechart.png'); 
}

It actually works fine, despite the fact that the output image is the same size as the SVG in the browser. How can i set a new size for the image? I also tried to get the size directly from the svg not the BBox, but it was the same.


Solution

  • Ok, thanks for the suggestions, i finally found a solution that perfectly fits (according to Cédric Hartlands hint). The viewbox attribute was the part that was completely missing in my code. The viewbox is defined as the following:

    viewbox = "x y width height"
    

    So to scale up the <svg> and ALL the elements in it, it is necessary to make sure that width and height of the viewbox exactly match the new width and height of the <svg> element:

    //original version
    <svg> width="100" height="100" viewbox="0 0 100 100" preserveAspectRatio="xMinYMin meet"</svg>
    
    //scaled up version
    <svg> width="200" height="200" viewbox="0 0 200 200" preserveAspectRatio="xMinYMin meet"</svg>
    

    If i convert the scaled up svg into a canvas, it fits the whole image without loosing any quality (which is the biggest benefit of vector graphics anyway). Cannot believe it took my so long to get that.