SVG to Canvas with d3.js


Has anyone tried using a svg to canvas library when creating d3.js visualizations? I've tried to use canvg.js and d3.js to convert svg to canvas from within an android 2.3 application webview, but when I call:

    .attr("class", "axis")
    .attr("transform", function(d) { return "rotate(" + angle(d) * 180 / Math.PI + ")"; })
        .scale(radius.copy().range([-5, -outerRadius]))
        function (d) {
            if (window.innerWidth < 455){
                console.log("innerWidth less than 455: ",window.innerWidth);
                return -(window.innerHeight * .33);
            else {
                console.log("innerWidth greater than 455: ",window.innerWidth);
                return -(window.innerHeight * .33);
    .attr("dy", ".71em")
    .attr("text-anchor", "middle")
    .text(function(d, i) { return capitalMeta[i]; })

I get the error: Uncaught TypeError: Cannot call method setProperty of null

Would some sort of headless browser application, or a server side js parser work? Has anyone encountered this before?

10/16/2018 4:57:54 PM

Here's one way you could write your svg to canvas (and then save the result as a png or whatever):

// Create an export button"body")

var w = 100, // or whatever your svg width is
    h = 100;

// Create the export function - this will just export 
// the first svg element it finds
function svgToCanvas(){
    // Select the first svg element
    var svg ="svg")[0][0],
        img = new Image(),
        serializer = new XMLSerializer(),
        svgStr = serializer.serializeToString(svg);

    img.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr);

    // You could also use the actual string without base64 encoding it:
    //img.src = "data:image/svg+xml;utf8," + svgStr;

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

    canvas.width = w;
    canvas.height = h;
    // Now save as png or whatever
5/14/2014 11:46:52 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow