我正在尝试将Google Graph的输出保存为图像并不断收到错误:
未捕获的TypeError:无法读取null的“firstChild”属性
这是javascript:
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Impressions', 'Clicks']
<?
while ($arrDate = mysql_fetch_assoc($resStats)) {
$arrDates[] = $arrDate;
echo ",['".$arrDate["fdate"]."', ".($arrDate["imps"] ? $arrDate["imps"] : 0).", ".($arrDate["clicks"] ? $arrDate["clicks"] : 0)."]";
}
?>
]);
var options = {
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 1}
},
vAxes:{
0: {title: 'Impressions', minValue: 0},
1: {title: 'Clicks', minValue: 0}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chartContainer'));
chart.draw(data, options);
}
function getImgData(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);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
function saveAsImg(chartContainer) {
var imgData = getImgData(chartContainer);
// Replacing the mime-type will force the browser to trigger a download
// rather than displaying the image in the browser window.
window.location = imgData.replace("image/png", "image/octet-stream");
}
function toImg(chartContainer, imgContainer) {
var doc = chartContainer.ownerDocument;
var img = doc.createElement('img');
img.src = getImgData(chartContainer);
while (imgContainer.firstChild) {
imgContainer.removeChild(imgContainer.firstChild);
}
imgContainer.appendChild(img);
}
那里的PHP输出如下:
['Date', 'Impressions', 'Clicks'],
['Aug 24, 2012', 2, 0],['Aug 27, 2012', 3, 0],['Aug 28, 2012', 37, 0],['Aug 29, 2012', 17, 0]
这是需要的按钮和div:
<button onclick="toImg(document.getElementById('chartContainer'), document.getElementById('img_div'));">Convert to image</button>
<div id="line_div"></div>
这个:http://jsfiddle.net/SCjm8/157/是我试图遵循的教程,但已经卡住了。有人可以告诉我如何制作它,以便当我点击代码中的按钮时,它会生成图像并将其放入Div中吗?
非常感谢