Created
June 1, 2013 05:36
-
-
Save geoff-parsons/5689383 to your computer and use it in GitHub Desktop.
Example of live updating Chart.js charts.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Chart.js Redraw Example</title> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> | |
<script type="text/javascript" charset="utf-8" src="chart.min.js"></script> | |
<script type="text/javascript" charset="utf-8"> | |
window.chartOptions = { | |
segmentShowStroke: false, | |
percentageInnerCutout: 75, | |
animation: false | |
}; | |
var chartUpdate = function(value) { | |
console.log("Updating Chart: ", value); | |
// Replace the chart canvas element | |
$('#chart').replaceWith('<canvas id="chart" width="300" height="300"></canvas>'); | |
// Draw the chart | |
var ctx = $('#chart').get(0).getContext("2d"); | |
new Chart(ctx).Doughnut([ | |
{ value: value, | |
color: '#4FD134' }, | |
{ value: 100-value, | |
color: '#DDDDDD' }], | |
window.chartOptions); | |
// Schedule next chart update tick | |
setTimeout (function() { chartUpdate(value - 1); }, 1000); | |
} | |
$(document).ready(function() { | |
setTimeout (function() { chartUpdate(99); }, 1000); | |
}) | |
</script> | |
</head> | |
<body> | |
<canvas id="chart" width="300" height="300"></canvas> | |
</body> | |
</html> |
Hi! I am new to js and other web development tools. Can you please tell me at what part of your code you are accessing your database server to plot the real-time graph?
Thanks in advance. :)
@Siddhant08 He isn't, he is using:
setTimeout (function() { chartUpdate(value - 1); }, 1000);
at the end of chartUpdate to call the function again with a different value, this is also known as recursive programming.
Replacing the canvas to update the chart is brilliant! I tried with Chart.update() but never got it to work.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have been looking for a solution for live updates of graphs. I stumbled across this and noticed that to do the update, you are creating a new graph and replacing the previous canvas.
This looks OK on your demo, but if you re-enable animations this redraws the animations rather than smoothly updating.
We can alter the segment data and utilise the .update() method (keeping the same canvas and chart object making the updates smooth and without replacing elements, giving an easy way to pull updates via ajax)
--- updated example ---