Layers · Angular, React and OpenLayers

Compare layers with a swipe

Build an interactive before-and-after OpenLayers layer swipe comparison between OpenStreetMap and Esri satellite imagery using prerender clipping.

A map of Kraków with OpenStreetMap left of the middle and satellite imagery right of it, and the layer comparison slider below it.
A screenshot of the example. Map data © OpenStreetMap contributors. Imagery: Esri World Imagery (Esri, Maxar, Earthstar Geographics and the GIS User Community).

What this example shows

Centred on Kraków, a single map viewport displays OpenStreetMap streets on the left side of a vertical split line and Esri World Imagery satellite photography on the right. Dragging the range slider below the map sweeps that vertical curtain smoothly between 2% and 98% across the city while panning and zooming move both layers as one.

When you need it

Before-and-after disaster assessments, historical vs modern orthophoto comparisons, and street-map vs aerial cross-checks are easiest to read when users sweep a divider directly across a single registered feature.

Implementing swipe via canvas clipping inside one OpenLayers map uses half the DOM/memory of two side-by-side maps and guarantees zero lag between halves.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

swipe.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceOsmComponent,
  SourceXYZComponent,
  ViewComponent,
} from 'cc-openlayers';
import RenderEvent from 'ol/render/Event';

/** Satellite imagery over OpenStreetMap, clipped at a slider position by the layer's prerender and postrender hooks. */
@Component({
  selector: 'app-swipe',
  imports: [
    CoordinateComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceOsmComponent,
    SourceXYZComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-view [zoom]="13"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-tile [prerender]="clip" [postrender]="restore">
        <aol-source-xyz
          url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
        />
      </aol-layer-tile>
    </aol-map>
    <div class="example-controls">
      <label>
        Layer comparison
        <input type="range" min="2" max="98" [value]="swipe()" (input)="setSwipe(number($event))" />
      </label>
    </div>
  `,
})
export class Swipe {
  readonly swipe = signal(50);
  private readonly map = viewChild.required(MapComponent);

  /** Clips the imagery to the part of the canvas right of the slider position. */
  protected readonly clip = (event: RenderEvent): void => {
    const context = event.context as CanvasRenderingContext2D | undefined;
    if (!context) return;
    const { width, height } = context.canvas;
    const left = (width * this.swipe()) / 100;
    context.save();
    context.beginPath();
    context.rect(left, 0, width - left, height);
    context.clip();
  };

  protected readonly restore = (event: RenderEvent): void => (event.context as CanvasRenderingContext2D)?.restore();

  protected setSwipe(value: number): void {
    this.swipe.set(value);
    this.map().instance.render();
  }

  protected number(event: Event): number {
    return (event.target as HTMLInputElement).valueAsNumber;
  }
}

Architecture and OpenLayers mechanics

OpenStreetMap renders normally across the full viewport as the bottom layer, while the upper satellite aol-layer-tile attaches [prerender] and [postrender] hooks. In [prerender], the handler computes the split X coordinate from the slider signal as a fraction of ctx.canvas.width (device pixels), defines a rectangular clip path from that X coordinate to the right edge of the canvas, and calls ctx.save() + ctx.clip().

[postrender] calls restore() to clean up the canvas state, and moving the range slider invokes render() on the map so the split curtain updates immediately at 60 fps even while the camera is stationary.

How it works

  • [prerender] and [postrender] on the upper satellite aol-layer-tile bracket tile drawing inside a dynamic right-hand rectangular clip region.
  • The split X coordinate multiplies the slider’s percentage signal against physical canvas width so the curtain aligns across the viewport.
  • Dragging the slider calls render() on the map instance to force an immediate repaint without moving the view.
  • Using physical backing-canvas dimensions (canvas.width / canvas.height or getRenderPixel) keeps the split line accurate on 2x/3x HiDPI displays.

Pitfalls

  • Forgetting restore() in [postrender] leaves the rectangular clip active on the shared canvas context and accidentally slices away subsequent vector layers drawn above the imagery.
  • Multiplying slider percentage by CSS clientWidth instead of physical backing-canvas width positions the split line halfway too far left on Retina screens (and ignores rotated backing canvases unless getRenderPixel is used).

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.