Accessing the SVG data through JavaScript

后端 未结 2 2066
既然无缘
既然无缘 2020-12-16 17:28

I am working on a web application using SVG & JS. Things are going well but I am a bit confused by data handling.

The data for objects that users create is dynam

2条回答
  •  暖寄归人
    2020-12-16 18:08

    The webkit bug mentioned in @Phrogz answer seems to have been fixed in more recent versions, so I found a solution that doesn't require a manual parse is

    // from http://bl.ocks.org/biovisualize/1209499
    // via https://groups.google.com/forum/?fromgroups=#!topic/d3-js/RnORDkLeS-Q
    var xml = d3.select("svg")
      .attr("title", "test2")
      .attr("version", 1.1)
      .attr("xmlns", "http://www.w3.org/2000/svg")
      .node().parentNode.innerHTML;
    
    // from http://webcache.googleusercontent.com/search?q=cache:http://phpepe.com/2012/07/export-raphael-graphic-to-image.html
    // via http://stackoverflow.com/questions/4216927/problem-saving-as-png-a-svg-generated-by-raphael-js-in-a-canvas
    var canvas = document.getElementById("myCanvas")
    canvg(canvas, svgfix(xml));
    document.location.href = canvas.toDataURL();
    

    which requires https://code.google.com/p/svgfix/ and https://code.google.com/p/canvg/ and uses d3.js to obtain the svg source, which should be doable without d3.js as well (but this takes care of adding required metadata which can lead to problems when missing).

提交回复
热议问题