Menu

Layer Cake

Layer Cake is a graphics framework for Svelte. It uses the measurements of your target div and your data extents to create scales that stay synced on layout changes. Use these scales to organize multiple, mostly-reusable Svelte components, whether they be SVG, HTML, Canvas or WebGL. Since they all share the same coordinate space, you can build your graphic one layer at a time. It can also be used to easily create responsive graphics server-side that work without JavaScript.

Unlike other libraries, chart components live inside your project, so you have complete control for customization. It also includes some handy helper functions to help format your data into the right shape.

Read the guide, try the starter template or check out the example components. See the examples below and even edit them live. Here's a sample of what the code looks like:

<script>
  // The library provides a main wrapper component
  // and a bunch empty layout components...
  import { LayerCake, Svg, Html, Canvas } from 'layercake';

  // ...that you fill with your own chart components,
  // that live inside your project and which you
  // can copy and paste from here as starting points.
  import AxisX from './components/AxisX.svelte';
  import AxisY from './components/AxisY.svelte';
  import Line from './components/Line.svelte';
  import Scatter from './components/Scatter.svelte';
  import Labels from './components/Labels.svelte';

  const data = [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }];
</script>

<style>
  .chart-container {
    width: 100%;
    height: 500px;
  }
</style>

<div class="chart-container">
  <LayerCake
    x='x'
    y='y'
    {data}
  >
    <Svg>
      <AxisX/>
      <AxisY/>
      <Line color='#f0c'/>
    </Svg>

    <Canvas>
      <Scatter color='#0fc'/>
    </Canvas>

    <Html>
      <Labels/>
    </Html>
  </LayerCake>
</div>

Server-side rendering

Svelte makes it easy to render your project server side and Layer Cake has built-in helpers to make it even easier for charts. All of these examples below (except for their canvas components) will load and be responsive without client-side JavaScript. The advantage is that you can see the chart as soon as the page loads, avoiding blank placeholder spaces. HTML charts use percentage-based scales and SVG charts take advanage of certain viewBox and CSS settings that Rich Harris, Svelte's creator, outlined in this blog post.

For shapes that are difficult to render using percentages, such as swoopy arrows, Layer Cake makes it easy to superimpose client-side components that will hydrate once JavaScript is available. See the annotated column example below.