score:1

Accepted answer

Use of canvg library simplifies all this :-)

https://github.com/canvg/canvg

contents.convertSvgToCanvas = function (sourceSvgId, canvasContainerId, canvasId, canvasWidth, canvasHeight, callback) {
    var serializer = new XMLSerializer();
    var svgNode = d3.select("#" + sourceSvgId).node();
    var devicePixelRatio = window.devicePixelRatio || 1;
    d3.select("#" + canvasContainerId).append("canvas")
        .attr("id", canvasId)
        .attr("width", (canvasWidth) * devicePixelRatio)
        .attr("height", (canvasHeight) * devicePixelRatio)
        .style("position", "absolute");
    if (svgNode) {
        var cv = document.getElementById(canvasId);
        var ctx = cv.getContext("2d");
        var pixelRatio = window.devicePixelRatio || 1;
        cv.style.width = cv.width + "px";
        cv.style.height = cv.height + "px";
        cv.width *= pixelRatio;
        cv.height *= pixelRatio;
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        canvg(document.getElementById(canvasId), serializer.serializeToString(svgNode));
        callback();
    }
};

Related Query

More Query from same tag