JSFiddle - React, Tailwind, and code Playground
HTML
Numbers: <input type="text" id="numbers" value="1, 0, 5, 4, 8, 10, 15, 10, 5, 4">
Fill: <input type="text" id="fill" value="#dcfce7">
Stroke: <input type="text" id="stroke" value="#bbf7d0">
Width: <input type="text" id="Width" value="100">
Height: <input type="text" id="Height" value="200">
<input type="button" id="submit" value="Submit">
<div id="output"></div>
JavaScript
class Sparkline {
constructor() {
this.stroke_width = 4;
}
path(points, vb_width, vb_height) {
return ["M", ...points.map((value, i) => {
let x = i;
let y = vb_height - value;
return `${x} ${y}${i < vb_width ? " L " : ""}`;
})];
}
closed_path(points, vb_width, vb_height) {
return [...this.path(points, vb_width, vb_height), ` L ${vb_width} ${vb_height} L 0 ${vb_height} Z`];
}
draw(width, height, points, fill,stroke) {
let vb_width = points.length - 1;
let vb_height = Math.max(...points);
return `
<svg height="${height}" width="${width}" viewBox="0 0 ${vb_width} ${vb_height}" preserveAspectRatio="none" role="img" xmlns="http://www.w3.org/2000/svg">
<path d="${this.closed_path(points, vb_width, vb_height).join('')}" stroke="transparent" fill="${fill}" />
<path d="${this.path(points, vb_width, vb_height).join('')}" stroke-width="${this.stroke_width}" vector-effect="non-scaling-stroke" stroke="${stroke}" fill="transparent" />
</svg>
`;
}
}
document.querySelector("#submit").addEventListener("click", () => {
//get the numbers input and convert to an array of numbers
let numbers = document.querySelector("#numbers").value;
let fill = document.querySelector("#fill").value;
let stroke = document.querySelector("#stroke").value;
let width = document.querySelector("#Width").value;
let height = document.querySelector("#Height").value;
let sparkline = new Sparkline();
let output = sparkline.draw(width, height, numbers.split(",").map(Number), fill, stroke);
document.querySelector("#output").innerHTML = output;
});