Commit d9c653d4 authored by Wolfgang Fellger's avatar Wolfgang Fellger

Add a simple graph for showing weights

parent e495b85c
WeightGraph = {
// Draw a simple graph in 2D context ctx using data and the given diagram width and height
// (axes and scales use an additional 100px in x and ~25px in y direction)
render: function(ctx, data, diagWidth, diagHeight) {
function translate(x, y) {
return {x: (x - xMin) * xScale, y: (y - yMax) * -yScale};
}
// Adjust diagram size to data
var xMin = data[0][0];
var xMax = data[data.length-1][0];
var yMin = Infinity;
var yMax = 0;
for (var x = 0; x < data.length; x++) {
if (data[x][1] < yMin)
yMin = Math.floor(data[x][1] / 5) * 5;
if (data[x][1] > yMax)
yMax = Math.ceil(data[x][1] / 5) * 5;
}
yMax += 0.5;
yMin -= 0.5;
var xLength = xMax - xMin;
var yLength = yMax - yMin;
var xScale = diagWidth / xLength;
var yScale = diagHeight / yLength;
ctx.save();
ctx.translate(50, 0);
// Draw diagram scales and guides
ctx.moveTo(-0.5,0);
ctx.lineTo(-0.5, diagHeight - 0.5);
ctx.lineTo(diagWidth, diagHeight - 0.5);
ctx.stroke();
ctx.save();
for (var x = 0; x < diagWidth; x += 100) {
time = new Date(xMin + x / xScale);
text = time.getDate() + '. ' + (time.getMonth() + 1) + '. ' + time.getFullYear();
ctx.beginPath();
ctx.moveTo(x - 0.5, diagHeight - 5);
ctx.lineTo(x - 0.5, diagHeight + 5);
ctx.stroke();
ctx.strokeText(text, x, diagHeight + 15, 100);
}
for (var y = Math.round(yMin); y < Math.round(yMax); y++) {
var translated = Math.round(translate(0, y).y - 0.5) + 0.5;
ctx.beginPath();
ctx.strokeStyle = '#ccc';
ctx.moveTo(-5, translated);
ctx.lineTo(diagWidth, translated);
ctx.stroke();
if (y % 2 == 0) {
ctx.strokeStyle = '#000';
ctx.strokeText(y + ' kg', -40, translated + 5, 50);
}
}
ctx.restore();
// Draw actual diagram
ctx.beginPath();
for (var x = 0; x < data.length; x++) {
translated = translate(data[x][0], data[x][1]);
ctx[x ? 'lineTo' : 'moveTo'](translated.x, translated.y);
}
ctx.stroke();
ctx.fillStyle = '#026';
for (var x = 0; x < data.length; x++) {
translated = translate(data[x][0], data[x][1]);
ctx.beginPath();
ctx.arc(translated.x, translated.y, 4, 0, Math.PI*2);
ctx.fill();
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment