问题
I am having a hard time to figure out how to do this, since i am not that familiar with google chart.
I am using pivotTable.js and everything is working okay, but i want to "save" or have a button where the current created chart will be cloned to another div.
I made a global variable
var wrapper;
this to save the chart
wrapper = new google.visualization.ChartWrapper({
dataTable: dataTable,
chartType: chartType,
options: options
});
wrapper.draw(result[0]);
After this, when the button is clicked the wrapper chart, should be redrawn in another div.
<div id="trial" style="margin: 30px;"></div>
I tried to do this but i am stock with how will i put the chart into the trial div.
// Never called.
google.visualization.events.addListener(wrapper, 'onmouseover', uselessHandler);
google.visualization.events.addListener(wrapper, 'ready', onReady);
// Never called
function uselessHandler() {
alert("I am never called!");
}
function onReady() {
google.visualization.events.addListener(wrapper.getChart(), 'click', usefulHandler);
}
// Called
function usefulHandler() {
alert(wrapper.getChart());
}
SOLVED:
function getChart() {
google.visualization.events.addListener(wrapper, 'ready', onReady);
function onReady() {
google.visualization.events.addListener(wrapper.getChart(), 'click', usefulHandler);
}
var trialChart = wrapper.clone();
trialChart.setContainerId('trial');
trialChart.draw();
}
回答1:
after clone()
-- just need to set the new containerId
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', '2015');
data.addColumn('number', '2016');
data.addRows([
[new Date('01/01/2016'), 200, 210],
[new Date('01/02/2016'), 190, 220],
[new Date('01/03/2016'), 205, 200],
[new Date('01/04/2016'), 220, 230],
[new Date('01/05/2016'), 212, 210],
[new Date('01/06/2016'), 185, 193],
[new Date('01/07/2016'), 196, 207]
]);
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_orig',
dataTable: data,
options: {
height: 400
}
});
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
document.getElementById('cloneBtn').addEventListener('click', function () {
var trialChart = chart.clone();
trialChart.setContainerId('chart_trial');
trialChart.draw();
}, false);
});
chart.draw();
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<input type="button" id="cloneBtn" value="Clone" />
<div>Original Chart</div>
<div id="chart_orig"></div>
<div>Trial Chart</div>
<div id="chart_trial"></div>
来源:https://stackoverflow.com/questions/38532646/how-to-clone-and-re-draw-google-chart-in-another-div