Skip to content

Instantly share code, notes, and snippets.

@geoff-parsons
Created June 1, 2013 05:36
Show Gist options
  • Save geoff-parsons/5689383 to your computer and use it in GitHub Desktop.
Save geoff-parsons/5689383 to your computer and use it in GitHub Desktop.
Example of live updating Chart.js charts.
<!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>
@Siddhant08
Copy link

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. :)

@RicardoVaranda
Copy link

@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.

https://en.wikipedia.org/wiki/Recursion_(computer_science)

@tomherold
Copy link

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