93 lines
2.2 KiB
JavaScript
93 lines
2.2 KiB
JavaScript
var gui = require('gui');
|
|
var gfx = gui.gfx;
|
|
|
|
var sp = 8;
|
|
|
|
// data
|
|
const datapoints = [
|
|
{ x: 0, v: 0 },
|
|
{ x: 1, v: 100 },
|
|
{ x: 2, v: -39 },
|
|
{ x: 3, v: -24 },
|
|
{ x: 4, v: 24 },
|
|
{ x: 5, v: -12 },
|
|
{ x: 6, v: 100 }
|
|
];
|
|
|
|
// create window (initial size; drawing will use current window client area)
|
|
let gadgets = [];
|
|
let win = gui.createWindow({
|
|
title: "Summary Chart",
|
|
width: 400,
|
|
height: 200,
|
|
left: 30,
|
|
top: 30,
|
|
gadgets: gadgets
|
|
});
|
|
|
|
// Compute cumulative series and min/max (include 0 to ensure Y=0 is visible)
|
|
let cumulative = [];
|
|
let cur = 0;
|
|
cumulative.push({ x: datapoints[0].x, y: 0 }); // start at 0
|
|
let lowest = 0;
|
|
let highest = 0;
|
|
|
|
for (let i = 0; i < datapoints.length; ++i) {
|
|
cur += datapoints[i].v;
|
|
cumulative.push({ x: datapoints[i].x, y: cur });
|
|
if (cur < lowest) lowest = cur;
|
|
if (cur > highest) highest = cur;
|
|
}
|
|
if (0 < lowest) lowest = 0;
|
|
if (0 > highest) highest = 0;
|
|
|
|
// Draw function using current window size
|
|
function drawChart() {
|
|
const totalW = Math.max(10, 400 - sp * 3);
|
|
const totalH = Math.max(10, 200 - sp * 3);
|
|
const left = sp;
|
|
const top = sp;
|
|
const right = left + totalW;
|
|
const bottom = top + totalH;
|
|
|
|
// X and Y ranges
|
|
const minX = cumulative[0].x;
|
|
const maxX = cumulative[cumulative.length - 1].x;
|
|
const xRange = (maxX === minX) ? 1 : (maxX - minX);
|
|
let yRange = highest - lowest;
|
|
if (yRange === 0) yRange = 1;
|
|
|
|
// mapping functions
|
|
const mapX = x => left + ((x - minX) / xRange) * totalW;
|
|
const mapY = y => bottom - ((y - lowest) / yRange) * totalH; // invert Y
|
|
|
|
// draw Y=0 axis
|
|
const y0 = mapY(0);
|
|
gfx.setColor(win, 1);
|
|
gfx.drawLine(win, left, y0, right, y0);
|
|
|
|
gfx.setColor(win, 4);
|
|
// draw polyline
|
|
let last = cumulative[0];
|
|
for (let i = 1; i < cumulative.length; ++i) {
|
|
let p = cumulative[i];
|
|
gfx.drawLine(win, mapX(last.x), mapY(last.y), mapX(p.x), mapY(p.y));
|
|
last = p;
|
|
}
|
|
}
|
|
|
|
// initial draw
|
|
drawChart();
|
|
|
|
while (true) {
|
|
var evt = gui.waitEvent(win);
|
|
if (!evt) continue;
|
|
|
|
if (evt.type === 'close') {
|
|
gui.closeWindow(win);
|
|
break;
|
|
}
|
|
}
|
|
|
|
console.log("close");
|