Last active
August 29, 2015 13:56
-
-
Save juanlopezdev/9214233 to your computer and use it in GitHub Desktop.
Exportar Google Chart a Imagen PNG / Export Google Chart to Image PNG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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