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.

The street map of Kraków shown only inside the city boundary, over a light grey map of the surrounding region at zoom 11.
A screenshot of the example. Base map: Esri World Light Gray Base (Esri, HERE, Garmin, OpenStreetMap contributors and the GIS user community). Boundary of Kraków: Państwowy Rejestr Granic © GUGiK. Map data © OpenStreetMap contributors.

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.ts
import { 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';
  };
}

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 to null so it supplies geometry without drawing strokes of its own.
  • Inside the street layer’s [postrender], getVectorContext paints the polygon with destination-in compositing to retain street pixels strictly inside the city boundary.
  • An addfeature listener 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-in cut and suddenly reveal uncut OpenStreetMap across the entire screen.
  • Give the background light-grey base layer its own className so 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.

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.