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.

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.tsimport { 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;
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
swipe.react.tsximport { useRef, useState, type ChangeEvent } from 'react';
import type OLMap from 'ol/Map';
import type RenderEvent from 'ol/render/Event';
import { Coordinate, DefaultInteractions, Map, OSMSource, TileLayer, View, XYZSource } from 'cc-openlayers/react';
/** Satellite imagery over OpenStreetMap, clipped at a slider position by the layer's prerender and postrender hooks. */
export function Swipe() {
const [swipe, setSwipeState] = useState(50);
/** The position the next frame clips at, set before the map is asked to render. */
const position = useRef(50);
const map = useRef<OLMap>(null);
/** Clips the imagery to the part of the canvas right of the slider position. */
const clip = (event: RenderEvent): void => {
const context = event.context as CanvasRenderingContext2D | undefined;
if (!context) return;
const { width, height } = context.canvas;
const left = (width * position.current) / 100;
context.save();
context.beginPath();
context.rect(left, 0, width - left, height);
context.clip();
};
const restore = (event: RenderEvent): void => (event.context as CanvasRenderingContext2D)?.restore();
const setSwipe = (value: number): void => {
position.current = value;
setSwipeState(value);
map.current?.render();
};
return (
<>
<Map ref={map} height="480px">
<DefaultInteractions />
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<TileLayer onPreRender={clip} onPostRender={restore}>
<XYZSource url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" />
</TileLayer>
</Map>
<div className="example-controls">
<label>
Layer comparison
<input
type="range"
min="2"
max="98"
value={swipe}
onChange={(event: ChangeEvent<HTMLInputElement>) => setSwipe(event.target.valueAsNumber)}
/>
</label>
</div>
</>
);
}How the React version works
Satellite imagery lies over OpenStreetMap and is clipped to the part of the canvas right of the slider.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection.
From Angular to React
| Angular | React |
|---|---|
[prerender], [postrender] on the imagery layer | onPreRender, onPostRender |
(input)="setSwipe(...)" and map.render() | the slider's onChange, map.current?.render() |
a signal read in clip | a useRef with the position, set before asking for a frame, because the frame can start before React renders |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular.
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 satelliteaol-layer-tilebracket 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).
Related examples
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.