Styling and labels · Angular, React and OpenLayers

Fill regions with local artwork

Clip custom decorative SVG artwork to Polish voivodeship polygon boundaries in OpenLayers using a Canvas 2D Style renderer and save/restore.

Polish voivodeships filled with striped decorative artwork against a dark background.
A screenshot of the example. Voivodeships: Państwowy Rejestr Granic © GUGiK. Illustrative artwork by ClearCraft.

What this example shows

Against a dark backdrop, Poland’s sixteen voivodeships loaded from local GeoJSON are filled with crisp striped decorative SVG artwork clipped cleanly to each province’s exact administrative border.

When you need it

Editorial maps, regional branding showcases, game maps and bespoke infographics sometimes fill each territory with unique full-extent artwork rather than a flat colour or tiny repeating hatch tile.

A custom OpenLayers Style renderer gives you full Canvas 2D path clipping over pre-projected pixel rings so arbitrary images conform cleanly to complex multi-part polygons.

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.

style-renderer.shared.ts
import type Feature from 'ol/Feature';
import type SimpleGeometry from 'ol/geom/SimpleGeometry';
import type VectorLayer from 'ol/layer/Vector';
import { unByKey } from 'ol/Observable';
import { getHeight, getWidth } from 'ol/extent';
import { toContext } from 'ol/render';
import type VectorSource from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import type { RenderFunction } from 'ol/style/Style';

// Illustrative regional artwork, not official flags or heraldic designs.
const COLORS = [
  '#e5b83b',
  '#cf414d',
  '#587c40',
  '#426f84',
  '#c6a455',
  '#bd424b',
  '#bd7341',
  '#618ca5',
  '#86a857',
  '#b95d74',
  '#5179a2',
  '#e4bc48',
  '#b96954',
  '#5b957f',
  '#c9564e',
  '#7590b0',
];
const fill = new Fill({ color: 'rgba(255,255,255,0)' });
const stroke = new Stroke({ color: 'rgba(255,255,255,0.8)', width: 2 });

export const renderRegion: RenderFunction = (pixels, state) => {
  const pattern: HTMLImageElement | undefined = state.feature.get('pattern');
  if (!pattern) return;

  const geometry = state.geometry.clone() as SimpleGeometry;
  geometry.setCoordinates(pixels);
  const extent = geometry.getExtent();
  const width = getWidth(extent);
  const height = getHeight(extent);
  if (width < 1 || height < 1) return;

  const context = state.context;
  context.save();
  try {
    const drawing = toContext(context, { pixelRatio: 1 });
    drawing.setFillStrokeStyle(fill, stroke);
    drawing.drawGeometry(geometry);
    context.clip();
    context.drawImage(pattern, extent[0], extent[1], width, height);
  } finally {
    context.restore();
  }
};

export function bindRegionPatterns(source: VectorSource, layer: VectorLayer): () => void {
  const pending = new Set<HTMLImageElement>();
  const visited = new WeakSet<Feature>();
  const release = (image: HTMLImageElement) => {
    image.onload = null;
    image.onerror = null;
    pending.delete(image);
  };
  const load = (feature: Feature) => {
    if (visited.has(feature)) return;
    visited.add(feature);
    const color = COLORS[Number(feature.get('code')) / 2 - 1] ?? '#7590b0';
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200" viewBox="0 0 320 200"><rect width="320" height="200" fill="${color}"/><path d="M0 40H320M0 100H320M0 160H320" stroke="#fff" stroke-opacity=".55" stroke-width="18"/><path d="M40 0L140 200M140 0L240 200M240 0L340 200" stroke="#172d44" stroke-opacity=".2" stroke-width="12"/></svg>`;
    const image = new Image();
    pending.add(image);
    image.onload = () => {
      release(image);
      feature.set('pattern', image);
      layer.changed();
    };
    image.onerror = () => release(image);
    image.src = `data:image/svg+xml,${encodeURIComponent(svg)}`;
  };
  const key = source.on('addfeature', (event) => {
    if (event.feature) load(event.feature);
  });
  source.getFeatures().forEach(load);
  return () => {
    unByKey(key);
    pending.forEach(release);
  };
}
style-renderer.ts
import { afterNextRender, ChangeDetectionStrategy, Component, DestroyRef, inject, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerVectorComponent,
  MapComponent,
  SourceGeoJSONComponent,
  StyleComponent,
  ViewComponent,
} from 'cc-openlayers';
import { bindRegionPatterns, renderRegion } from './style-renderer.shared';

/** Polish regions filled with locally prepared decorative images through a custom style renderer. */
@Component({
  selector: 'app-style-renderer',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerVectorComponent,
    MapComponent,
    SourceGeoJSONComponent,
    StyleComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default /><aol-control-defaults />
      <aol-view [zoom]="6"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-vector background="#1a2b39">
        <aol-style [renderer]="renderer" />
        <aol-source-geojson url="assets/poland/voivodeships.geojson" featureProjection="EPSG:3857" />
      </aol-layer-vector>
    </aol-map>
    <div class="example-controls">
      <p class="example-hint">Each region is filled with an illustrative local pattern.</p>
    </div>
  `,
})
export class StyleRenderer {
  protected readonly renderer = renderRegion;
  private readonly source = viewChild.required(SourceGeoJSONComponent);
  private readonly layer = viewChild.required(LayerVectorComponent);
  constructor() {
    const destroy = inject(DestroyRef);
    afterNextRender(() => destroy.onDestroy(bindRegionPatterns(this.source().instance, this.layer().instance)));
  }
}

Architecture and OpenLayers mechanics

Shared setup loads local voivodeship GeoJSON boundaries alongside generated SVG images. On each render pass, the custom Style renderer saves the 2D canvas context, traces the feature’s pixel-space polygon rings (including any multi-polygon parts), clips the context to that path, draws the region’s artwork across its pixel bounding box, and restores the context immediately afterward.

Both Angular and React implementations release source listeners cleanly when destroyed.

How it works

  • Local GeoJSON provides the sixteen voivodeship boundaries while generated SVG assets provide illustrative fills.
  • The custom Style renderer traces pixel-space polygon rings to clip each image cleanly inside its provincial border.
  • Shared lifecycle management loads images once and detaches listeners on component teardown.

Pitfalls

  • Always bracket custom canvas clipping inside context save and restore calls so one province’s clip path never leaks onto subsequent features or layers.
  • Generated striped graphics are purely illustrative demonstration artwork rather than official heraldic flags or coats of arms.

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.