使用d3.js将SVG转换为Canvas

19

有没有人在创建d3.js可视化时尝试过使用将svg转换为canvas的库?我曾经尝试过在Android 2.3应用程序Webview中使用canvg.js和d3.js将svg转换为canvas,但当我调用以下内容时:

svg.selectAll(".axis")
    .data(d3.range(angle.domain()[1]))
    .enter().append("g")
    .attr("class", "axis")
    .attr("transform", function(d) { return "rotate(" + angle(d) * 180 / Math.PI + ")"; })
    .call(d3.svg.axis()
        .scale(radius.copy().range([-5, -outerRadius]))
        .ticks(5)
        .orient("left"))
    .append("text")
    .attr("y", 
        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]; })
    .attr("style","font-size:12px;");
我遇到了错误: 未捕获的类型错误: 无法调用null的方法 setProperty http://mbostock.github.com/d3/d3.js?2.5.0:1707 是否可以使用无头浏览器应用程序或服务器端js解析器来解决?有人遇到过这种情况吗?
4个回答

26

这里是将 SVG 写入画布并将结果保存为 PNG 或其他格式的方法之一:

// Create an export button
d3.select("body")
    .append("button")
    .html("Export")
    .on("click",svgToCanvas);

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 = d3.select("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");
    document.body.appendChild(canvas);

    canvas.width = w;
    canvas.height = h;
    canvas.getContext("2d").drawImage(img,0,0,w,h);
    // Now save as png or whatever
};

2
好的答案!我还添加了以下解决方案(基于您的解决方案),它从外部CSS样式表中引用样式。 - Constantino
1
@ace,我能拿到完整的代码吗?我真的很需要。 - sg28
@ace,也许可以用plnkr/fiddle。 - sg28

12

@ace的回答非常好,但它不能处理外部CSS样式表的情况。我的下面的示例将自动为生成的图像添加与原始SVG完全相同的样式,即使它从单独的样式表中获取样式。

// when called, will open a new tab with the SVG
// which can then be right-clicked and 'save as...'
function saveSVG(){

    // get styles from all required stylesheets
    // http://www.coffeegnome.net/converting-svg-to-png-with-canvg/
    var style = "\n";
    var requiredSheets = ['phylogram_d3.css', 'open_sans.css']; // list of required CSS
    for (var i=0; i<document.styleSheets.length; i++) {
        var sheet = document.styleSheets[i];
        if (sheet.href) {
            var sheetName = sheet.href.split('/').pop();
            if (requiredSheets.indexOf(sheetName) != -1) {
                var rules = sheet.rules;
                if (rules) {
                    for (var j=0; j<rules.length; j++) {
                        style += (rules[j].cssText + '\n');
                    }
                }
            }
        }
    }

    var svg = d3.select("svg"),
        img = new Image(),
        serializer = new XMLSerializer(),

    // prepend style to svg
    svg.insert('defs',":first-child")
    d3.select("svg defs")
        .append('style')
        .attr('type','text/css')
        .html(style);


    // generate IMG in new tab
    var svgStr = serializer.serializeToString(svg.node());
    img.src = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(svgStr)));
    window.open().document.write('<img src="' + img.src + '"/>');
};

而且为了完整起见,调用函数的按钮:

// save button
d3.select('body')
    .append("button")
    .on("click",saveSVG)
    .attr('class', 'btn btn-success')

这非常有帮助,但是你的示例在requiredSheets和document.styleSheets方面存在混淆,这导致我遇到了一些错误。我通过删除var requiredSheets ...if(requiredSheets.indexOf ...(这意味着我可以删除var sheetName ...)来修复它们。也就是说,requiredSheets是不必要的,会导致错误,并且可以安全地删除。 - Matthew Grivich
@Constantino:heightwidth从未被使用 - 为什么要给它们赋值? - Shafique Jamal

1

我没有尝试过使用库,但是根据MDN上this的帖子,我已经将由d3生成的SVG呈现到画布上了。

这段代码是MDN和一些jQuery的快速混搭,你需要整理一下,它没有错误或平台检查,但它能够工作,我希望它能帮到你。

$(document.body).append(
    '<canvas id="canvas" width="'+diameter+'" height="'+diameter+'"></canvas>'
);

// https://developer.mozilla.org/en/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
var el = $($('svg')[0]);
var svgMarkup = '<svg xmlns="http://www.w3.org/2000/svg"'
+ ' class="'  + el.attr('class') +'"'
+ ' width="'  + el.attr('width') +'"'
+ ' height="' + el.attr('height') +'"'
+ '>'
+ $('svg')[0].innerHTML.toString()+'</svg>';
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = this.URL || this.webkitURL || this;
var img = new Image();
var svg = new Blob([svgMarkup], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
    ctx.drawImage(img, 0, 0);
    alert('ok');
    DOMURL.revokeObjectURL(url);
};
img.src = url;

1

你尝试在支持SVG的浏览器上使用相同的代码吗?看看是否是Webview的问题?然后尝试使用canvg this example 或使用DOM序列化this one。对于服务器端渲染,你可以从this example开始,了解如何使用Node.js将其呈现到canvas上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接