Skip to content

Instantly share code, notes, and snippets.

@raxityo
Last active July 10, 2023 14:54
Show Gist options
  • Save raxityo/73f5786f30eacc8dfbb3b38d58dce882 to your computer and use it in GitHub Desktop.
Save raxityo/73f5786f30eacc8dfbb3b38d58dce882 to your computer and use it in GitHub Desktop.
Draw Sparkline chart, converted by ChatGPT from https://alexplescan.com/posts/2023/07/08/easy-svg-sparklines/
// Define the default fill and stroke colors
const defaultFill = "#dcfce7";
const defaultStroke = "#bbf7d0";
// Define the stroke width
const strokeWidth = 4;
/**
* Draws a sparkline SVG based on the given width, height and points
* @param {number} width - The width of the SVG element
* @param {number} height - The height of the SVG element
* @param {number[]} points - The array of points to plot
* @param {string} [fill=defaultFill] - The fill color of the area under the curve
* @param {string} [stroke=defaultStroke] - The stroke color of the curve
* @returns {string} The SVG markup
*/
function draw(width, height, points, fill = defaultFill, stroke = defaultStroke) {
// Calculate the viewbox dimensions based on the points
let vbWidth = points.length - 1;
let vbHeight = Math.max(...points);
// Return the SVG markup with the paths and attributes
return `
<svg height="${height}" width="${width}" viewBox="0 0 ${vbWidth} ${vbHeight}" preserveAspectRatio="none" role="img" xmlns="http://www.w3.org/2000/svg">
<path d="${closedPath(points, vbWidth, vbHeight)}" stroke="transparent" fill="${fill}" />
<path d="${path(points, vbWidth, vbHeight)}" stroke-width="${strokeWidth}" vector-effect="non-scaling-stroke" stroke="${stroke}" fill="transparent" />
</svg>
`;
}
/**
* Generates the path for the curve
* @param {number[]} points - The array of points to plot
* @param {number} vbWidth - The viewbox width
* @param {number} vbHeight - The viewbox height
* @returns {string} The path data
*/
const path = (points, vbWidth, vbHeight) => [
"M",
points
.map((value, i) => {
let x = i;
let y = vbHeight - value;
return `${x} ${y}${i < vbWidth ? " L " : ""}`;
})
.join("")
].join("");
/**
* Generates the path for the area under the curve
* @param {number[]} points - The array of points to plot
* @param {number} vbWidth - The viewbox width
* @param {number} vbHeight - The viewbox height
* @returns {string} The path data
*/
const closedPath = (points, vbWidth, vbHeight) => [
path(points, vbWidth, vbHeight),
` L ${vbWidth} ${vbHeight} L 0 ${vbHeight} Z`
].join("");
// Export the draw function as a module
module.exports = draw;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment