LayerCake Svelte Graphics Framework

10.0.2 · active · verified Sun Apr 19

LayerCake is a lightweight, opinionated graphics framework designed for building highly customizable and reusable data visualizations with Svelte. It emphasizes a clear separation between the data layering, scaling, and rendering logic, allowing developers to bring their own Svelte components for charts and annotations. The current stable version is 10.0.2, with major versions released somewhat frequently to align with Svelte's evolution (e.g., Svelte 5 'Runes' support in v9/v10). Key differentiators include its Svelte-native component approach, making it highly composable and performant within a Svelte application, and its flexibility in rendering to SVG, HTML, or Canvas elements without dictating visual styles.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a basic LayerCake chart using `LayerCake` as the primary wrapper, and rendering different chart elements to `Svg`, `Canvas`, and `Html` containers. It also shows how to define accessor functions for data properties.

<script lang="ts">
  import { LayerCake, Svg, Html, Canvas } from 'layercake';
  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, label: 'Point A' },
    { x: 1, y: 2, label: 'Point B' },
    { x: 2, y: 3, label: 'Point C' }
  ];

  // Example of how you might pass context values as slot props
  // If you define 'x' and 'y' props on LayerCake, these will be available
  // to descendant components via context or slot props.
  function getX(d: typeof data[0]) { return d.x; }
  function getY(d: typeof data[0]) { return d.y; }
</script>

<style>
  .chart-container {
    width: 100%;
    max-width: 800px;
    height: 500px;
    border: 1px solid #eee;
    margin: 20px auto;
  }
</style>

<div class="chart-container">
  <LayerCake
    x={getX}
    y={getY}
    {data}
  >
    <Svg let:x let:y let:width let:height>
      <!-- Svg provides scales and dimensions via slot props -->
      <AxisX/>
      <AxisY/>
      <Line color='#f0c'/>
    </Svg>

    <Canvas let:xScale let:yScale let:data>
      <!-- Canvas components draw to a canvas element -->
      <Scatter color='#0fc'/>
    </Canvas>

    <Html>
      <!-- Html components render standard HTML elements -->
      <Labels/>
    </Html>
  </LayerCake>
</div>

view raw JSON →