I'm trying to get a toy D3 Svelte component going to explore integration strategies between the two. I'm trying to leverage Svelte bindings and D3 scales to let the chart rescale to the viewport; it seems to break the chart:
Last active
May 17, 2020 17:20
-
-
Save ixxie/b38fae5fcb61b617e03b333e5d3617e8 to your computer and use it in GitHub Desktop.
Svelte + D3
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
<script> | |
import * as d3 from "d3"; | |
import { width, height } from './store.js'; | |
import Chart from './Chart.svelte'; | |
let data = [ 1, 2, 4, 8, 16, 32 ]; | |
$: xScale = d3.scaleLinear() | |
.domain(d3.extent(data)) | |
.range([0, $width]); | |
$: yScale = d3.scaleLinear() | |
.domain([0, data.length]) | |
.range([0, $height]); | |
</script> | |
<style> | |
.viewport { | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
<div class='viewport' bind:clientWidth={$width} bind:clientHeight={$height}> | |
<p>width: {$width}, height: {$height}</p> | |
<Chart {data} {xScale} {yScale}/> | |
</div> |
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
<script> | |
export let data; | |
export let xScale; | |
export let yScale; | |
import * as d3 from "d3"; | |
import { onMount } from "svelte"; | |
onMount(()=> { | |
d3.select("svg") | |
.selectAll("circle") | |
.data(data) | |
.join("circle") | |
.attr("r", 10) | |
.attr("cx", (d, i) => xScale(d)) | |
.attr("cy", (d, i) => yScale(i)); | |
}); | |
</script> | |
<style> | |
svg { | |
width: 100%; | |
height: 100%; | |
} | |
circle { | |
fill: blueviolet; | |
stroke: rgb(255, 0, 212); | |
stroke-width: 10px; | |
} | |
</style> | |
<svg> | |
{#each data as point} | |
<circle></circle> | |
{/each} | |
</svg> |
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
import { writable } from 'svelte/store'; | |
export const width = writable(0); | |
export const height = writable(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment