Converting Google Chart into Image

2020-03-27 06:23发布

问题:

I'm trying convert a Google Chart into a image like this link but I don't understand about the line

var chartArea = chartContainer.getElementsByTagName('iframe')[0].contentDocument.getElementById('chartArea');

The code generated by the Google Chart, doesn't create any iFrame or elements called chartArea

Can someone help me ?

UPDATED

Follow the source of the generated by the chart, when I transform him into a image

http://chart.googleapis.com/chart?cht=lc&chs=500x200&chtt=Acessos%20ao%20im%C3%B3vel%20dos%20ultimos%20sete%20dias&chxt=x%2Cy&chxl=0%3A%7C24%2F01%7C25%2F01%7C26%2F01%7C27%2F01%7C28%2F01%7C29%2F01%7C30%2F01%7C1%3A%7C%7C0%7C&chdlp=r&chdl=San%7CSite%7CAtendimento&chco=ff8a00%2C585857%2C5501ff&chd=e%3Af.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.

回答1:

This can be done by following the steps on this page. Note that the code in the article is based on an old version of Google Visualization which used iframes, and will not work as posted. However, you can do the same using the following code (found in the comments):

var svg = $(chartContainer).find('svg').parent().html();
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('style', 'position: absolute; ' + '');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData; 

Note: I did not create this code, it was originally created by the author of the above site (Riccardo Govoni) and updated in the comments section by user Thomas.



回答2:

You can get a PNG version of your chart using chart.getImageURI() like following:

Needs to be after the chart is drawn, so in the ready event!

var my_div = document.getElementById('my_div');
var my_chart = new google.visualization.ChartType(chart_div);

google.visualization.events.addListener(my_chart, 'ready', function () {
  my_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
});

my_chart.draw(data);