Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
chartjs.org dynamic loading example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Charty Crap</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
</head>
<body>
<canvas id="chart" width="400" height="200"></canvas>
<script>
var mainChart;
var to_2digit = function(number){
return new Intl.NumberFormat('en-US',{minimumIntegerDigits: 2}).format(number);
};
var to_tag = function(date){
return to_2digit(date.getUTCDate()) +
to_2digit(date.getUTCMonth() + 1) +
date.getUTCFullYear();
};
var gimme_tags = function(from, to){
var tags = [];
var pivot = new Date(from);
tags.push(to_tag(pivot));
while((to - pivot) > 0){
pivot.setDate(pivot.getDate() + 1);
tags.push(to_tag(pivot));
}
return tags;
};
var gimme_tag_data = function(tag){
return {"tag": tag, "event": Math.floor(Math.random() * 100)};
};
var gimme_tags_data = function(tags){
var data = [];
for(var i=0;i<tags.length;i++){
data.push(gimme_tag_data(tags[i])['event']);
}
return data;
};
var gimme_empty_data = function(length, value){
var data = [];
for(var i=0;i<length;i++) data.push(value);
return data;
};
var request_data_for_tags = function(tags){
tags.forEach(function(tag, i){ request_data_for_tag(tag, i); });
};
var request_data_for_tag = function(tag, index){
mainChart.scale.xLabels[index] = '...';
window.setTimeout(function(){
var data = gimme_tag_data(tag);
mainChart.datasets[0].points[index].value = data['event'];
mainChart.scale.xLabels[index] = tag;
mainChart.update();
},
Math.random() * 10000);
};
var draw_chart = function(from, to){
if(mainChart) mainChart.destroy();
var tags = gimme_tags(from, to);
var data = {
labels: tags,
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,0.8)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: gimme_empty_data(tags.length, 0)
}
]
};
var ctx = document.getElementById("chart").getContext("2d");
mainChart = new Chart(ctx).Line(data, {bezierCurve: false});
mainChart.scale.beginAtZero = true;
request_data_for_tags(tags);
};
(function(){
draw_chart(new Date(2016, 0, 1), new Date(2016, 0, 10));
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.