var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [1, 3, 5, 7, 10, 15],
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
<div style="width: 500px; height: 500px">
<canvas id="myChart" width="400" height="400" style="width: 400px !important"></canvas>
</div>
<script src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"> </script>
通过使用 chartjs,我们是否有可能更改 json 数据并立即反映更改? 因为我们计划将图表与数据表连接,因此当用户应用过滤器时,JSON 数据将更改,并且图表必须立即更改! 如何使用 chartjs 做到这一点?
var ctx = document.getElementById("myChart").getContext('2d');
var myData = [1, 3, 5, 7, 10, 15];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: myData,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
function updateData(chart, labels, mydata) {
//if(labels) chart.data.labels = labels;
//chart.data.datasets.forEach((dataset) => {
// dataset.data[0]++; // Or you can cheng data like this
//});
chart.update();
}
setInterval(function(){
myData[0]++;
updateData(myChart,null,myData);
},1000);
<div style="width: 500px; height: 500px">
<canvas id="myChart" width="400" height="400" style="width: 400px !important"></canvas>
</div>
<script src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"> </script>