Menu

Multilayer map (canvas + svg)Edit

A canvas layer and an SVG layer. This technique is useful if you have a background layer that would require a large number of DOM nodes. Rendering that layer with canvas will speed up the page. The shapes you actually care about are in SVG to make styling and mouse interaction easier.

To render server-side, this example uses the fixedAspectRatio property, which the user sets ahead of time. The Canvas layer is rendered client side.

<script>
  import { LayerCake, ScaledSvg, Canvas } from 'layercake';
  import { feature } from 'topojson';
  import { geoAlbersUsa } from 'd3-geo';

  import MapSvg from './components/Map.svg.svelte';
  import MapCanvas from './components/Map.canvas.svelte';

  import usStates from './data/us-states.topojson.js';

  const geojson = feature(usStates, usStates.objects.collection);
  const aspectRatio = 2.63;
</script>

<style>
  .chart-container {
    position: relative;
    width: 100%;
  }
</style>

<div class="chart-container" style="padding-bottom:{100 / aspectRatio}%">
  <LayerCake
    position={'absolute'}
    data={geojson}
  >
    <Canvas>
      <MapCanvas
        projection={geoAlbersUsa}
      />
    </Canvas>
  </LayerCake>

  <LayerCake
    position='absolute'
    ssr={true}
    data={geojson}
  >
    <ScaledSvg
      fixedAspectRatio={aspectRatio}
    >
      <MapSvg
        fixedAspectRatio={aspectRatio}
        projection={geoAlbersUsa}
        features={geojson.features.slice(40, 50)}
      />
    </ScaledSvg>
  </LayerCake>
</div>