ChartJS : Zoomable and pannable temperature chart with live update from server
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom"></script>
<div style="width: 100%; margin: auto;">
<canvas id="temperatureChart"></canvas>
</div>
JavaScript
const PI = Math.PI;
function daysIntoYear(date){
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
function secondsToDhms(seconds) {
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return dDisplay + hDisplay + mDisplay + sDisplay;
}
function dataSimulation(from, to, grouping)
{
const timeDiff = (new Date(to) - new Date(from)) / 1000;
console.log("fromDate="+from+" toDate="+to+ " diff="+secondsToDhms(timeDiff)+ " group="+secondsToDhms(grouping));
datamapped = [];
dataEvery = 60*20; // Data get every 20mn
min = 999;
max = -999;
i = 0;
sum = 0;
for(x = new Date(from).getTime() ; x <= new Date(to).getTime() ; x = x + 1000*dataEvery)
{
date = new Date(x);
H = date.getHours();
M = date.getMinutes();
month = date.getMonth();
day = date.getDate();
nday = daysIntoYear(date);
value = day + (H / 100) + (M / 10000); // simple simulation
value = 20 + (10 * Math.sin(nday * (PI / 180))) + 3 * Math.sin(H * (360/24) * (PI/180)); // more complex
sum = sum + value;
if (value > max)
max = value;
if (value < min)
min = value;
if ((i * dataEvery) > grouping)
{
datamapped.push({
x:new Date(x).toISOString(),
min:min,
max:max,
avg:sum / i
});
i = 0;
sum = 0;
min = 999;
max = -999;
}
i = i + 1;
}
return datamapped;
}
async function fetchData(from, to, group) {
/**
...