将Google量规表另存为png [英] save google gauge chart as a png
问题描述
我使用的是Google图表,并有一个混合图表页面,一些饼图,一个柱形图和一个量规图
页面具有生成pdf的选项,因此我将图表转换为PNG以在pdf中使用..
所有图表都是以相同的方式生成的,使用div来显示Google图表,使用隐藏的div来存储png图像
var chart = new google.visualization.Gauge(document.getElementById('gauge'));var hidden =新的google.visualization.Gauge(document.getElementById('gauge_hidden'));//等待图表完成绘制,然后再调用getImageURI()方法.google.visualization.events.addListener(图表,就绪",函数(){gauge_hidden.innerHTML ='< img src ='+ chart.getImageURI()+'">';});chart.draw(数据,选项);
此代码在饼图和柱形图上都可以正常工作,但在我看到的量表上
chart.getImageURI不是函数
关于如何获得png的任何想法?
欢呼声
我也遇到了同样的问题,但是经过一番阅读后,我得出了这个解决方案:
我正在使用jQuery来简化此操作.
首先,使用XMLSerializer将SVG图表转换为字符串,然后使用btoa将其转换为base64.您可以通过以下方式使用此字符串:
var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);var base64String ="data:image/svg + xml; base64," + window.btoa(s);
就我而言,我需要将压力表绘制为PDF,而DOMPDF不支持此格式,因此,如果需要"data:image/png; base64"字符串,则可以继续使用此解决方案./p>
您需要将"svg + xml; base64"设置为新图像的src,然后将该图像绘制到画布上.之后,您可以使用画布上的toDataURL方法将内容获取为base64 png.
var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);var image = new Image();image.width = 640;image.height = 480;image.src ='data:image/svg + xml; base64,'+ window.btoa(s);var myCanvas = document.createElement('canvas');myCanvas.width = 640;myCanvas.height = 480;var myCanvasContext = myCanvas.getContext('2d');myCanvasContext.drawImage(image,0,0);//将Google Chart Gague转换为base64,是的!var base64String = myCanvas.toDataURL();
感谢此答案和此 this code works fin on he pie and column charts, but on the gauge chart I am seeing chart.getImageURI is not a function any ideas how I can get the png? CHeers I was facing this same issue, but after some reading i've come to this solution: I'm using jQuery to make this a little easier. First, use XMLSerializer to convert the SVG chart to a string and then use btoa to convert that to base64.
You can use this string this way: In my case i needed to draw the gauge chart to a PDF and DOMPDF doesn't support this format, so if you need a "data:image/png;base64," string, you can continue with this solution. You need to set the "svg+xml;base64" as src of a new Image and then draw that image to a Canvas. After that you can use toDataURL method from canvas to get the content as base64 png.
Thanks to the author of this answer and this post 这篇关于将Google量规表另存为png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var base64String = "data:image/svg+xml;base64," + window.btoa(s);
var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var image = new Image();
image.width = 640;
image.height = 480;
image.src = 'data:image/svg+xml;base64,' + window.btoa(s);
var myCanvas = document.createElement('canvas');
myCanvas.width = 640;
myCanvas.height = 480;
var myCanvasContext = myCanvas.getContext('2d');
myCanvasContext.drawImage(image,0,0);
// get google chart gague to base64, yey!
var base64String = myCanvas.toDataURL();