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.

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.tsimport 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.tsimport { 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)));
}
} 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.
style-renderer.react.tsximport { useEffect, useState } from 'react';
import type OLVectorLayer from 'ol/layer/Vector';
import type OLVectorSource from 'ol/source/Vector';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
GeoJSONSource,
Map,
Style,
VectorLayer,
View,
} from 'cc-openlayers/react';
import { bindRegionPatterns, renderRegion } from './style-renderer.shared';
/** Polish regions filled with locally prepared decorative images through a custom style renderer. */
export function StyleRenderer() {
const [source, setSource] = useState<OLVectorSource | null>(null);
const [layer, setLayer] = useState<OLVectorLayer | null>(null);
useEffect(() => {
if (source && layer) return bindRegionPatterns(source, layer);
}, [source, layer]);
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={6}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<VectorLayer ref={setLayer} background="#1a2b39">
<Style renderer={renderRegion} />
<GeoJSONSource ref={setSource} url="assets/poland/voivodeships.geojson" featureProjection="EPSG:3857" />
</VectorLayer>
</Map>
<div className="example-controls">
<p className="example-hint">Each region is filled with an illustrative local pattern.</p>
</div>
</>
);
}style-renderer.shared.tsimport 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);
};
}How the React version works
Clip decorative SVG images to the outlines of Polish voivodeships with a custom OpenLayers style renderer.
What both versions share
Both versions share the custom pixel renderer and the image-loading binding. That binding handles features already loaded and those arriving later. The decorative images are local SVG data URLs, so the renderer needs no external image host or API key.
From Angular to React
| Angular | React |
|---|---|
| afterNextRender establishes the image binding | useEffect establishes the image binding |
| viewChild reads the source and layer | refs hold the source and layer |
| DestroyRef releases the binding | effect cleanup releases the binding |
Who creates, updates and disposes
The binding starts once the layer and source exist. Loaded images are attached to their features and trigger a redraw. Cleanup removes the source listener and clears callbacks on pending images so a late load cannot update the destroyed view.
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.
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.