Last active
July 7, 2017 16:52
-
-
Save coderdiaz/4cce25b11a6797fac59eba816ebb731d to your computer and use it in GitHub Desktop.
Render Custom Legends
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
//Git it! Thank you very much! | |
var weightChartOptions = { | |
responsive: true, | |
legendCallback: function(chart) { | |
console.log(chart); | |
var legendHtml = []; | |
legendHtml.push('<table>'); | |
legendHtml.push('<tr>'); | |
for (var i=0; i<chart.data.datasets.length; i++) { | |
legendHtml.push('<td><div class="chart-legend" style="background-color:' + chart.data.datasets[i].backgroundColor + '"></div></td>'); | |
if (chart.data.datasets[i].label) { | |
legendHtml.push('<td class="chart-legend-label-text" onclick="updateDataset(event, ' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ')">' + chart.data.datasets[i].label + '</td>'); | |
} | |
} | |
legendHtml.push('</tr>'); | |
legendHtml.push('</table>'); | |
return legendHtml.join(""); | |
}, | |
legend: { | |
display: false | |
} | |
}; | |
// Show/hide chart by click legend | |
updateDataset = function(e, datasetIndex) { | |
var index = datasetIndex; | |
var ci = e.view.weightChart; | |
var meta = ci.getDatasetMeta(index); | |
// See controller.isDatasetVisible comment | |
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null; | |
// We hid a dataset ... rerender the chart | |
ci.update(); | |
}; | |
var ctx = document.getElementById("weightChart").getContext("2d"); | |
window.weightChart = new Chart(ctx, { | |
type: 'line', | |
data: weightChartData, | |
options: weightChartOptions | |
}); | |
document.getElementById("weightChartLegend").innerHTML = weightChart.generateLegend(); | |
}; | |
// The most important parts are: | |
// onClick function call for each legend label | |
if (chart.data.datasets[i].label) { | |
legendHtml.push('<td class="chart-legend-label-text" onclick="updateDataset(event, ' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ')">' + chart.data.datasets[i].label + '</td>'); | |
} | |
// and function | |
updateDataset = function(e, datasetIndex) { | |
var index = datasetIndex; | |
var ci = e.view.weightChart; | |
var meta = ci.getDatasetMeta(index); | |
// See controller.isDatasetVisible comment | |
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null; | |
// We hid a dataset ... rerender the chart | |
ci.update(); | |
}; | |
// Also make chart instance of Window adding window. before: | |
window.weightChart = new Chart(ctx, { | |
type: 'line', | |
data: weightChartData, | |
options: weightChartOptions | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment