Skip to content

Instantly share code, notes, and snippets.

@briandeheus
Created April 1, 2020 09:18
Show Gist options
  • Select an option

  • Save briandeheus/f8957c3b6c148b3aaea3de690210bb69 to your computer and use it in GitHub Desktop.

Select an option

Save briandeheus/f8957c3b6c148b3aaea3de690210bb69 to your computer and use it in GitHub Desktop.

Revisions

  1. briandeheus created this gist Apr 1, 2020.
    60 changes: 60 additions & 0 deletions spark.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    const Spark = ({
    height = 20,
    width = 140,
    series = [],
    color = "#4CAF50",
    backgroundColor = "#37474F",
    radius = 3,
    padding = [4, 4]
    }) => {
    const max = series.reduce((p, c) => {
    return c > p ? c : p;
    }, series[0]);

    if (Array.isArray(padding) === false) {
    padding = [padding, padding];
    }

    const paddingX = padding[0];
    const paddingY = padding[1];

    const maxX = width - paddingX * 2;
    const maxY = height - paddingY * 2;
    const yOffset = maxY / max;
    const xOffset = maxX / (series.length - 1);

    console.log("Max x =>", maxX, "max y =>", maxY);

    const seriesElms = series.map((value, index) => {
    const y = maxY - yOffset * value + paddingY;
    const x = index * xOffset + paddingX;
    console.log("Value =>", value, "x =>", x, "y =>", y);

    return (
    <React.Fragment key={index}>
    <circle cy={y} cx={x} r={radius} fill={color} />
    {series.length - 1 !== index && (
    <line
    x1={x}
    y1={y}
    x2={(index + 1) * xOffset + paddingX}
    y2={maxY - yOffset * series[index + 1] + paddingY}
    stroke={color}
    strokeWidth={1}
    />
    )}
    </React.Fragment>
    );
    });

    return (
    <svg
    height={height}
    width={width}
    style={{ backgroundColor }}
    className="spark-chart"
    >
    {seriesElms}
    </svg>
    );
    };