At the moment I havent found a solution to actually "link directly" to a chart (see later). But it is possible to convert the charts to images / PNG, and that is the prerequisity. And by converting on the fly you can let users save the chart as an image to a file.
The modern google charts is build up in a <svg> tag. The content of this tag can be drawn on a <canvas>
using the excellent canvg library.
When that is done, you can transfer the content of the canvas to an <img>
by canvas.toDataURL
. Here is an example :
First, include the canvg library
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
Some markup - 3 tags, a <div>
for the chart, a <canvas>
and a <img>
<div id="chart_div" style="width: 400px; height: 300px"></div>
<canvas id="canvas"></canvas>
<img id="img" width="200">
Notice "width=200"
for the image, just to demonstrate this actually is working :)
Draw a chart as "normal" (as anyone are used to do it), here minimalistic just for the test
function drawLineGraph() {
var data = new google.visualization.DataTable(someJSON);
chart = new google.visualization.BarChart(document.getElementById("chart_div"));
var options = {};
chart.draw(data, options);
}
Draw the chart on window.load
. I use a setTimeout
for effect, but in a real life scenario I think it would be best to use a google.visualization.events.addListener(xxx, 'ready', function
.
window.onload = function() {
drawLineGraph();
setTimeout(function() {
//get SVG content
var chart = document.getElementById('chart_div').getElementsByTagName('svg')[0].parentNode;
var svg = chart.innerHTML;
//get the canvas, adjust width / height
var canvas = document.getElementById('canvas');
canvas.setAttribute('width', chart.offsetWidth);
canvas.setAttribute('height', chart.offsetHeight);
//transfer SVG to canvas by canvg
canvg(canvas, svg);
//get an image source by canvas.toDataURL and add to the image
var imgsrc = canvas.toDataURL("image/png");
document.getElementById('img').setAttribute('src', imgsrc);
}, 1000);
}
The src of the image will look something like :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAYAAADtt+XCAAAdCklEQVR4Xu2dfcyWZfnHDyFwtZVz68WcJWO9UCRuD4T9KjdrJC0HI8wWbmiTGMJPiXBg8bL+IIhioxio4aaiZIPZCxi9qCtro/ZsCatZGzSiLdZcNtwSwugX8Ou8Nhji88B5f0+vPdf5fD
..
..
Of course going on and on....As normal. I have not yet tried to manipulate / remote link / sent this - only used it as image - but I am sure that this is quite easy!
Result / output for the code above :