Skip to content

Instantly share code, notes, and snippets.

@malted
Created November 23, 2021 20:41
Show Gist options
  • Save malted/c22f2f4cb6c6800d55fc4f29a098baa2 to your computer and use it in GitHub Desktop.
Save malted/c22f2f4cb6c6800d55fc4f29a098baa2 to your computer and use it in GitHub Desktop.
Fully Dynamic Svelte Graph Component
<script>
import { onMount } from 'svelte';
import { fly } from "svelte/transition";
let ready = false;
onMount(() => ready = true);
const dataset = [
{ name: "Apple", price: 6 },
{ name: "Orange", price: 5 },
{ name: "Pear", price: 2 }
];
dataset.highest = () => {
let h = 0;
Object.values(dataset).forEach(data => {
h = data.price > h ? data.price : h;
});
return h;
}
const highest = dataset.highest();
const barGapMultiplier = 3;
const barWidth = 20;
const barHeightMultiplier = 30;
</script>
<svg
width={dataset.length * barWidth * barGapMultiplier}
height={highest * barHeightMultiplier}
>
{#if ready}
{#each dataset as datapoint, i}
<rect
x={i * barWidth * barGapMultiplier}
y={(highest-datapoint.price) * barHeightMultiplier}
width={barWidth}
height={datapoint.price * barHeightMultiplier}
style="fill: grey"
in:fly={{ y: 200, duration: 2000, delay: i*500}}
/>
{/each}
{/if}
</svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment