Created
October 18, 2023 22:49
-
-
Save oxmix/b88e2e2175c11e48310cf96b1f96d07b to your computer and use it in GitHub Desktop.
Mini Chart in SVG Area Curve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const width = 300 | |
const height = 50 | |
const graph = [1, 2, 5, 0, 5, 0.2, 0.3, 0.4, 3, 9] | |
const peakVal = Math.max(...graph) | |
graph.unshift(0) // dot start | |
graph.push(0) // dot end | |
const part = width / (graph.length - 1) | |
const points = [] | |
for (const i in graph) { | |
points.push({ | |
x: i * part, | |
y: -(graph[i] * height / peakVal) + height | |
}) | |
} | |
let curve = `M${points[0].x},${points[0].y}` | |
catmullRom2bezier(points).forEach(c => { | |
curve += `C${c[0].x},${c[0].y} ${c[1].x},${c[1].y} ${c[2].x},${c[2].y} ` | |
}) | |
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') | |
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg') | |
svg.setAttribute('width', width) | |
svg.setAttribute('height', height) | |
const path = document.createElementNS("http://www.w3.org/2000/svg", "path") | |
path.setAttribute('d', curve.trim()) | |
svg.appendChild(path) | |
document.documentElement.innerHTML = `<style>body {background: black;} svg path {fill: rgba(255,255,255,.3)}</style>` | |
document.documentElement.appendChild(svg) | |
function catmullRom2bezier(points) { | |
const res = [] | |
for (let i = 0; i < points.length - 1; i++) { | |
const p = [] | |
p.push({ | |
x: points[Math.max(i - 1, 0)].x, | |
y: points[Math.max(i - 1, 0)].y | |
}) | |
p.push({ | |
x: points[i].x, | |
y: points[i].y | |
}) | |
p.push({ | |
x: points[i + 1].x, | |
y: points[i + 1].y | |
}) | |
p.push({ | |
x: points[Math.min(i + 2, points.length - 1)].x, | |
y: points[Math.min(i + 2, points.length - 1)].y | |
}) | |
const bp = [] | |
bp.push({ | |
x: +((-p[0].x + 6 * p[1].x + p[2].x) / 6).toFixed(1), | |
y: +((-p[0].y + 6 * p[1].y + p[2].y) / 6).toFixed(1) | |
}) | |
bp.push({ | |
x: +((p[1].x + 6 * p[2].x - p[3].x) / 6).toFixed(1), | |
y: +((p[1].y + 6 * p[2].y - p[3].y) / 6).toFixed(1) | |
}) | |
bp.push({ | |
x: +p[2].x.toFixed(1), | |
y: +p[2].y.toFixed(1) | |
}) | |
res.push(bp) | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment