Layers · Angular, React and OpenLayers
Clip a layer to a polygon
Clip an OpenLayers tile layer to Kraków’s exact GeoJSON municipal polygon using destination-in canvas compositing and getVectorContext.

What this example shows
At zoom 11 across the Kraków metropolitan area, detailed OpenStreetMap street cartography appears strictly inside the real, irregular administrative border of the City of Kraków, standing out vividly against a muted Esri World Light Gray basemap covering surrounding municipalities.
When you need it
Municipal geoportals, urban planning studies, national park guides and project-site presentations frequently highlight their exact study jurisdiction in full colour while keeping neighbouring territory subdued for geographic context.
Clipping dynamically from a live GeoJSON boundary eliminates pre-baking inverted raster mask tiles whenever municipal or project borders change.
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.
layer-clipping-vector.tsimport { afterNextRender, ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type { Extent } from 'ol/extent';
import GeoJSON from 'ol/format/GeoJSON';
import { getVectorContext } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
const style = new Style({ fill: new Fill({ color: '#000000' }) });
/**
* OpenStreetMap clipped to the boundary of Kraków (PRG) over Esri's light grey canvas: after the OpenStreetMap layer
* renders, the city's polygon is drawn on its canvas with `destination-in`, which keeps only the map inside it.
*/
@Component({
selector: 'app-layer-clipping-vector',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceImageTileComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="11">
<aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
</aol-view>
<!-- A distinct className is required to use another canvas for the background -->
<aol-layer-tile className="light-gray">
<aol-source-imagetile
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
[maxZoom]="16"
attributions="Tiles © Esri — Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community"
/>
</aol-layer-tile>
<aol-layer-tile [extent]="extent()" [postrender]="clip"><aol-source-osm /></aol-layer-tile>
<aol-layer-vector [style]="null">
<aol-source-vector url="assets/poland/krakow.geojson" [format]="format" attributions="Boundaries: PRG, GUGiK" />
</aol-layer-vector>
</aol-map>
`,
})
export class LayerClippingVector {
/**
* The extent of the clipping polygons: giving the clipped layer an extent is necessary to avoid rendering when the
* feature is outside the viewport.
*/
readonly extent = signal<Extent | undefined>(undefined);
protected readonly format = new GeoJSON();
private readonly city = viewChild.required(SourceVectorComponent);
constructor() {
afterNextRender(() => {
const source = this.city().instance;
source.on('addfeature', () => this.extent.set(source.getExtent().slice()));
});
}
protected readonly clip = (event: RenderEvent): void => {
const vectorContext = getVectorContext(event);
const context = event.context as CanvasRenderingContext2D;
context.globalCompositeOperation = 'destination-in';
this.city().instance.forEachFeature((feature) => {
vectorContext.drawFeature(feature, style);
});
context.globalCompositeOperation = 'source-over';
};
} 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.
layer-clipping-vector.react.tsximport { useRef, useState } from 'react';
import type { Extent } from 'ol/extent';
import GeoJSON from 'ol/format/GeoJSON';
import { getVectorContext } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style';
import type OLVectorSource from 'ol/source/Vector';
import type { VectorSourceEvent } from 'ol/source/Vector';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageTileSource,
Map,
OSMSource,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const style = new Style({ fill: new Fill({ color: '#000000' }) });
const format = new GeoJSON();
/**
* OpenStreetMap clipped to the boundary of Kraków (PRG) over Esri's light grey canvas: after the OpenStreetMap layer
* renders, the city's polygon is drawn on its canvas with `destination-in`, which keeps only the map inside it.
*/
export function LayerClippingVector() {
/**
* The extent of the clipping polygons: giving the clipped layer an extent is necessary to avoid rendering when the
* feature is outside the viewport.
*/
const [extent, setExtent] = useState<Extent | undefined>(undefined);
const city = useRef<OLVectorSource>(null);
const clip = (event: RenderEvent): void => {
const vectorContext = getVectorContext(event);
const context = event.context as CanvasRenderingContext2D;
context.globalCompositeOperation = 'destination-in';
city.current?.forEachFeature((feature) => {
vectorContext.drawFeature(feature, style);
});
context.globalCompositeOperation = 'source-over';
};
return (
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={11}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
{/* A distinct className is required to use another canvas for the background */}
<TileLayer className="light-gray">
<ImageTileSource
url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
maxZoom={16}
attributions="Tiles © Esri — Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community"
/>
</TileLayer>
<TileLayer extent={extent} onPostRender={clip}>
<OSMSource />
</TileLayer>
<VectorLayer style={null}>
<VectorSource
ref={city}
url="assets/poland/krakow.geojson"
format={format}
attributions="Boundaries: PRG, GUGiK"
onAddFeature={(event: VectorSourceEvent) => setExtent(event.target.getExtent().slice())}
/>
</VectorLayer>
</Map>
);
}How the React version works
After OpenStreetMap renders, Kraków's polygon is drawn on its canvas in destination-in mode, which keeps only the map inside the city. Esri's grey map lies below on a canvas of its own.
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. The city border (PRG) is assets/poland/krakow.geojson.
From Angular to React
| Angular | React |
|---|---|
[postrender]="clip" on the OSM layer | onPostRender={clip} on TileLayer |
an addfeature listener in afterNextRender | onAddFeature on VectorSource |
[extent]="extent()" | extent={extent} from state set once the border has loaded |
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
Three pieces cooperate cleanly: first, a muted light-grey base layer renders with its own distinct className so it occupies a separate lower <canvas>. Second, an invisible helper vector layer ([style] set to null) loads Kraków’s GeoJSON polygon and, on addfeature, copies the polygon’s bounding box into the street layer’s [extent].
Third, in the street layer’s [postrender] hook—after OpenStreetMap tiles have painted onto their own upper canvas—getVectorContext draws the GeoJSON polygon using Canvas 2D globalCompositeOperation = "destination-in" with an opaque fill, erasing every street-tile pixel outside the municipal polygon while preserving everything inside.
How it works
- A helper vector layer loads Kraków’s GeoJSON border with
[style]set tonullso it supplies geometry without drawing strokes of its own. - Inside the street layer’s
[postrender],getVectorContextpaints the polygon withdestination-incompositing to retain street pixels strictly inside the city boundary. - An
addfeaturelistener copies the polygon’s bounding box to the street layer’s [extent] so OpenStreetMap skips rendering and tile loading whenever Kraków leaves the screen.
Pitfalls
- Setting the street layer’s [extent] from the polygon bounds is mandatory, not just an optimisation: OpenLayers culls vector geometries outside the viewport, so without [extent], panning away from Kraków would skip the
destination-incut and suddenly reveal uncut OpenStreetMap across the entire screen. - Give the background light-grey base layer its own
classNameso OpenLayers does not merge both tile layers onto one shared canvas and erase the background outside the city too. - Until the asynchronous GeoJSON boundary finishes loading, hide the clipped layer (or wait for
addfeature) if you want to avoid a brief initial uncut frame.
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.