JSFiddle - React, Tailwind, and code Playground
by Amir Danish
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.1/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id='line'>line</button>
<button id='bar'>bar</button>
<canvas id="canvas"></canvas>
JavaScript
var config = {
type: 'line',
data: {
labels: ["June", "July", "August", "September", "October", "November", "December"],
datasets: [{
label: "company1",
data: [1, 1, 2, 3, 4, 5, 6],
fill: false,
borderColor: "purple",
backgroundColor: "purple"
}, {
label: "company2",
data: [1, 2, 4, 8, 3, 2, 4],
fill: false,
borderColor: "green",
backgroundColor: "green"
}]
},
options: {
responsive: true,
}
};
var myChart;
$("#line").click(function() {
change('line');
});
$("#bar").click(function() {
change('bar');
});
function change(newType) {
var ctx = document.getElementById("canvas").getContext("2d");
// Remove the old chart and all its event handles
if (myChart) {
myChart.destroy();
}
// Chart.js modifies the object you pass in. Pass a copy of the object so we can use the original object later
var temp = jQuery.extend(true, {}, config);
temp.type = newType;
myChart = new Chart(ctx, temp);
};