Skip to content

Instantly share code, notes, and snippets.

@ixxie
Last active May 17, 2020 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ixxie/b38fae5fcb61b617e03b333e5d3617e8 to your computer and use it in GitHub Desktop.
Save ixxie/b38fae5fcb61b617e03b333e5d3617e8 to your computer and use it in GitHub Desktop.
Svelte + D3

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:

<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>
<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>
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