basic graph drawing

feature/frontend-charts
Kenneth Barbour 2020-07-21 18:59:26 -04:00
parent cb53a49210
commit 73dafb29b8
1 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,51 @@
import m from 'mithril';
function normalize(x, min, max) {
return (x - min)/(max - min);
}
class Graph {
view(vnode) {
const { title, width, height, margins, origin, maximums, data } = {...Graph.defaults, ...vnode.attrs};
const tx = (x, y) => {
const normalized = [normalize(x, origin[0], maximums[0]), normalize(y, origin[1], maximums[1])];
const dataWidth = width - margins[1] - margins[3];
const dataHeight = height - margins[0] - margins[2];
console.log('tx',{x,y, normalized});
return [normalized[0] * dataWidth + margins[3], ((1-normalized[1]) * dataHeight) + margins[0]];
}
return (
<div class="Graph-container">
<svg width="100%" viewBox={`0 0 ${width} ${height}`}>
{title && <title>{title}</title>}
<rect x="0" y="0" width={width} height={height} fill="none" stroke="#000" stroke-width=".1" />
{ /* Bottom margin */ }
<line x1={margins[3]} y1={height-margins[2]} x2={width-margins[1]} y2={height-margins[2]} stroke="#000" stroke-width=".1" />
{ /* Left margin */ }
<line x1={margins[3]} y1={margins[0]} x2={margins[3]} y2={height-margins[2]} stroke="#000" stroke-width=".1" />
{data.map((datum, i) => {
const translated = tx(datum[0],datum[1]);
const [x, y] = tx(...datum);
console.log({translated, datum});
return (<circle cx={x} cy={y} r=".5" fill="#000" />)
})}
</svg>
</div>
);
}
}
Graph.defaults = {
title: false,
width: 100,
height: 40,
margins: [5, 3, 2, 3], // top right bottom left
origin: [0, 0],
maximums: [100, 100],
data: [[0,0], [100,0], [100, 100], [0, 100], [25,60]],
}
export default Graph;