Skip to content

Instantly share code, notes, and snippets.

@juanlopezdev
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save juanlopezdev/9214233 to your computer and use it in GitHub Desktop.

Select an option

Save juanlopezdev/9214233 to your computer and use it in GitHub Desktop.
Exportar Google Chart a Imagen PNG / Export Google Chart to Image PNG
/**
* Requested
* <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/canvg.js"></script>
* /
/**
* Convert object to a canvas object
*/
function getImgCanvas(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
return canvas;
}
/**
* Download Image
*/
function downloadImg(canvas, filename) {
// create an "off-screen" anchor tag
var lnk = document.createElement('a'),e;
/// the key here is to set the download attribute of the a tag
lnk.download = filename;
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
lnk.href = canvas.toDataURL("image/png;base64");
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
} else if (lnk.fireEvent) {
lnk.fireEvent("onclick");
}
}
/**
* Save Image
*/
function saveToImg(container_id, filename) {
var canvas = getImgCanvas(document.getElementById(container_id));
downloadImg(canvas, filename);
}
/**
* USE
* $("#btn_download").click(function() {
* saveToImg("content_id", "image.png");
* });
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment