-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart_utils.js
More file actions
59 lines (50 loc) · 1.64 KB
/
chart_utils.js
File metadata and controls
59 lines (50 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Chart {
constructor(canvas, label) {
this.ctx = canvas.getContext("2d");
this.canvas = canvas;
this.data = [];
this.label = label;
this.maxData = 0;
this.generation = 0;
}
push(value) {
this.data.push(value);
this.generation++;
if (value > this.maxData) this.maxData = value;
this.draw();
}
draw() {
const ctx = this.ctx;
const w = this.canvas.width;
const h = this.canvas.height;
const margin = 20;
ctx.clearRect(0, 0, w, h);
// Draw axes
ctx.beginPath();
ctx.strokeStyle = "rgba(230, 225, 229, 0.2)"; // OnSurface Variant
ctx.lineWidth = 1;
ctx.moveTo(margin, margin);
ctx.lineTo(margin, h - margin);
ctx.lineTo(w - margin, h - margin);
ctx.stroke();
// Draw Label
ctx.fillStyle = "#E6E1E5"; // OnSurface
ctx.textAlign = "center";
ctx.font = "500 11px 'Google Sans', 'Roboto', sans-serif";
ctx.fillText(this.label, w / 2, margin / 2 + 5);
// Draw Data
if (this.data.length < 2) return;
ctx.beginPath();
ctx.strokeStyle = "#A8C7FA"; // MD3 Primary (Blue Light)
ctx.lineWidth = 2;
const xStep = (w - 2 * margin) / (this.data.length - 1);
const yScale = (h - 2 * margin) / this.maxData;
for (let i = 0; i < this.data.length; i++) {
const x = margin + i * xStep;
const y = h - margin - this.data[i] * yScale;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
}
}