最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Save a Google Chart as SVG? - Stack Overflow

programmeradmin1浏览0评论

The new Google Chart API creates charts as SVGs (not PNGs as it used to). I'd like to be able to save the generated SVG. How can I do this?

If I use Chrome to inspect elements on the page, I can find the svg tag that holds the SVG. I'd like to be able to get the generated SVG using JavaScript. I'd prefer not to search the HTML source for the svg tag in JavaScript, and if there's a way to get the SVG string directly from the chart object (maybe the ChartWrapper class?) that would be preferable.

The new Google Chart API creates charts as SVGs (not PNGs as it used to). I'd like to be able to save the generated SVG. How can I do this?

If I use Chrome to inspect elements on the page, I can find the svg tag that holds the SVG. I'd like to be able to get the generated SVG using JavaScript. I'd prefer not to search the HTML source for the svg tag in JavaScript, and if there's a way to get the SVG string directly from the chart object (maybe the ChartWrapper class?) that would be preferable.

Share Improve this question asked Oct 2, 2012 at 20:43 CornstalksCornstalks 38.2k19 gold badges83 silver badges149 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

Apparently, this is not supported by the Google Charts API (references 1, 2, and 3). I created the below hack to get the SVG string as a workaround. Below is the full JavaScript.

function drawVisualization() {
    // Create and populate the data table.
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work', 11],
        ['Eat', 2],
        ['Commute', 2],
        ['Watch TV', 2],
        ['Sleep', 7]
        ]);

    // Create and draw the visualization.
    var chart = new google.visualization.PieChart(document.getElementById('visualization'));
    google.visualization.events.addListener(chart, 'ready', allReady); // ADD LISTENER
    chart.draw(data, {title:"So, how was your day?"});
}

function allReady() {
    var e = document.getElementById('visualization');
    // svg elements don't have inner/outerHTML properties, so use the parents
    alert(e.getElementsByTagName('svg')[0].outerHTML);
}

google.setOnLoadCallback(drawVisualization);

Note that this doesn't work in IE because the Google Charts API doesn't use SVG in IE. I'm always open to better solutions.

(thanks to untill for suggesting .outerHTML over .parentNode.innerHTML)

You can also use Google Chrome DevTools, especially the element selector then you can copy/past the SVG you're looking for directly from the DOM.

发布评论

评论列表(0)

  1. 暂无评论