Layers · Angular, React and OpenLayers
A magnifier over imagery
Build a 2x pixel magnifier loupe over OpenLayers aerial imagery by resampling canvas pixels with getImageData and putImageData in postrender.

What this example shows
Hovering over GUGiK’s aerial orthophotomap of central Kraków at zoom 13 opens a circular 2x magnifying loupe framed by a translucent white ring right under the pointer—enlarging roofs, courtyards and market stalls around the Main Square to double size without changing the overall map zoom.
When you need it
Inspecting dense cadastral labels, fine orthophoto features or utility symbols normally forces users to zoom in and lose regional context, then zoom back out again.
A cursor-following loupe magnifies the spot under inspection instantaneously with zero extra tile downloads or camera jumps.
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.
magnify.tsimport { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import { getTopLeft, getWidth } from 'ol/extent';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { Pixel } from 'ol/pixel';
import { EXTENT } from 'ol/proj/epsg3857';
import { getRenderPixel } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
MapComponent,
SourceTileWMTSComponent,
TileGridWMTSComponent,
ViewComponent,
} from 'cc-openlayers';
const size = getWidth(EXTENT) / 256;
/** A magnifier that oversamples the orthophoto around the pointer; the arrow keys resize it. */
@Component({
selector: 'app-magnify',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
MapComponent,
SourceTileWMTSComponent,
TileGridWMTSComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { '(document:keydown)': 'resize($event)' },
template: `
<aol-map height="480px" (pointerMove)="move($event)" (mouseout)="leave()">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="13"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
<aol-layer-tile [postrender]="magnify">
<aol-source-tilewmts
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
crossOrigin="anonymous"
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
layer="ORTOFOTOMAPA"
matrixSet="EPSG:3857"
format="image/jpeg"
projection="EPSG:3857"
[style]="'default'"
[wrapX]="true"
>
<aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
</aol-source-tilewmts>
</aol-layer-tile>
</aol-map>
<div class="example-controls">
<p class="example-hint">Move over the map to magnify it. Use the ↑ and ↓ keys to resize the magnifier.</p>
<label
>Radius <output>{{ radius() }}</output></label
>
</div>
`,
})
export class Magnify {
protected readonly origin = getTopLeft(EXTENT);
protected readonly resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
protected readonly matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
protected readonly radius = signal(75);
private readonly mousePosition = signal<Pixel | null>(null);
private readonly map = viewChild.required(MapComponent);
/** Draws the pixels around the pointer twice as large, inside a circle. */
protected readonly magnify = (event: RenderEvent): void => {
const position = this.mousePosition();
if (!position) return;
const radius = this.radius();
const pixel = getRenderPixel(event, position);
const offset = getRenderPixel(event, [position[0] + radius, position[1]]);
const half = Math.hypot(offset[0] - pixel[0], offset[1] - pixel[1]);
const context = event.context as CanvasRenderingContext2D;
const [centerX, centerY] = pixel;
const originX = centerX - half;
const originY = centerY - half;
const side = Math.round(2 * half + 1);
const sourceData = context.getImageData(originX, originY, side, side).data;
const magnified = context.createImageData(side, side);
for (let j = 0; j < side; ++j) {
for (let i = 0; i < side; ++i) {
const dI = i - half;
const dJ = j - half;
const inside = Math.hypot(dI, dJ) < half;
const sourceI = inside ? Math.round(half + dI / 2) : i;
const sourceJ = inside ? Math.round(half + dJ / 2) : j;
const destOffset = (j * side + i) * 4;
const sourceOffset = (sourceJ * side + sourceI) * 4;
for (let channel = 0; channel < 4; ++channel) {
magnified.data[destOffset + channel] = sourceData[sourceOffset + channel];
}
}
}
context.save();
context.beginPath();
context.arc(centerX, centerY, half, 0, 2 * Math.PI);
context.lineWidth = (3 * half) / radius;
context.strokeStyle = 'rgba(255,255,255,0.5)';
context.putImageData(magnified, originX, originY);
context.stroke();
context.restore();
};
protected move(event: MapBrowserEvent): void {
this.mousePosition.set(event.pixel);
this.map().instance.render();
}
protected leave(): void {
this.mousePosition.set(null);
this.map().instance.render();
}
protected resize(event: KeyboardEvent): void {
if (event.key === 'ArrowUp') this.radius.update((radius) => Math.min(radius + 5, 150));
else if (event.key === 'ArrowDown') this.radius.update((radius) => Math.max(radius - 5, 25));
else return;
this.map().instance.render();
event.preventDefault();
}
} 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.
magnify.react.tsximport { useEffect, useRef, useState } from 'react';
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';
import type OLMap from 'ol/Map';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { Pixel } from 'ol/pixel';
import { getRenderPixel } from 'ol/render';
import type RenderEvent from 'ol/render/Event';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Map,
TileLayer,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
const size = getWidth(EXTENT) / 256;
const origin = getTopLeft(EXTENT);
const resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
const matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
/** A magnifier that oversamples the orthophoto around the pointer; the arrow keys resize it. */
export function Magnify() {
const tileGrid = useWMTSTileGrid({ origin, resolutions, matrixIds });
const [radius, setRadius] = useState(75);
/** The radius the next frame draws with, set before the map is asked to render. */
const currentRadius = useRef(75);
const mousePosition = useRef<Pixel | null>(null);
const map = useRef<OLMap>(null);
/** Draws the pixels around the pointer twice as large, inside a circle. */
const magnify = (event: RenderEvent): void => {
const position = mousePosition.current;
if (!position) return;
const radius = currentRadius.current;
const pixel = getRenderPixel(event, position);
const offset = getRenderPixel(event, [position[0] + radius, position[1]]);
const half = Math.hypot(offset[0] - pixel[0], offset[1] - pixel[1]);
const context = event.context as CanvasRenderingContext2D;
const [centerX, centerY] = pixel;
const originX = centerX - half;
const originY = centerY - half;
const side = Math.round(2 * half + 1);
const sourceData = context.getImageData(originX, originY, side, side).data;
const magnified = context.createImageData(side, side);
for (let j = 0; j < side; ++j) {
for (let i = 0; i < side; ++i) {
const dI = i - half;
const dJ = j - half;
const inside = Math.hypot(dI, dJ) < half;
const sourceI = inside ? Math.round(half + dI / 2) : i;
const sourceJ = inside ? Math.round(half + dJ / 2) : j;
const destOffset = (j * side + i) * 4;
const sourceOffset = (sourceJ * side + sourceI) * 4;
for (let channel = 0; channel < 4; ++channel) {
magnified.data[destOffset + channel] = sourceData[sourceOffset + channel];
}
}
}
context.save();
context.beginPath();
context.arc(centerX, centerY, half, 0, 2 * Math.PI);
context.lineWidth = (3 * half) / radius;
context.strokeStyle = 'rgba(255,255,255,0.5)';
context.putImageData(magnified, originX, originY);
context.stroke();
context.restore();
};
const move = (event: MapBrowserEvent): void => {
mousePosition.current = event.pixel;
map.current?.render();
};
const leave = (): void => {
mousePosition.current = null;
map.current?.render();
};
useEffect(() => {
const resize = (event: KeyboardEvent): void => {
if (event.key === 'ArrowUp') currentRadius.current = Math.min(currentRadius.current + 5, 150);
else if (event.key === 'ArrowDown') currentRadius.current = Math.max(currentRadius.current - 5, 25);
else return;
setRadius(currentRadius.current);
map.current?.render();
event.preventDefault();
};
document.addEventListener('keydown', resize);
return () => document.removeEventListener('keydown', resize);
}, []);
return (
<>
<div onMouseOut={leave}>
<Map ref={map} height="480px" onPointerMove={move}>
<DefaultInteractions />
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer onPostRender={magnify}>
<WMTSSource
attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
crossOrigin="anonymous"
url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
layer="ORTOFOTOMAPA"
matrixSet="EPSG:3857"
format="image/jpeg"
projection="EPSG:3857"
style="default"
wrapX={true}
tileGrid={tileGrid}
/>
</TileLayer>
</Map>
</div>
<div className="example-controls">
<p className="example-hint">Move over the map to magnify it. Use the ↑ and ↓ keys to resize the magnifier.</p>
<label>
Radius <output>{radius}</output>
</label>
</div>
</>
);
}How the React version works
Around the cursor, the orthophoto's pixels show magnified twice in a circle; the arrow keys change the radius from 25 to 150.
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. Both versions compute the WMTS tile grid of GUGiK's orthophoto (origin, 20 resolutions, ids EPSG:3857:z) in the same way; in React the useWMTSTileGrid hook creates it once from module constants. The pixel magnification loop is the same in both versions.
From Angular to React
| Angular | React |
|---|---|
(pointerMove), (mouseout) on aol-map | onPointerMove on Map and <div onMouseOut={leave}> around it |
host: { '(document:keydown)': … } | useEffect with a keydown listener |
[postrender]="magnify" | onPostRender={magnify} |
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
After the orthophoto layer finishes painting its tiles onto its canvas, [postrender] converts the pointer coordinate into physical backing-canvas pixels via getRenderPixel and reads the surrounding square block of RGBA pixels with getImageData. For every pixel inside the loupe radius, the sampler copies the colour located halfway toward the circle’s centre—producing a clean 2x optical zoom around the cursor—and writes the modified buffer back with putImageData before stroking a circular ring bracketed by save() and restore().
Crucially, the WMTS tile source sets crossOrigin so tiles arrive with CORS headers; without CORS clearance, the browser marks the canvas tainted and blocks pixel reads.
How it works
- In
[postrender],getImageDatareads rendered pixels around the cursor and remaps each interior pixel from halfway to the centre for 2x magnification. putImageDatawrites the resampled pixel square back inside a block opened bysave()and closed byrestore(), which then strokes the white ring; pixels outside the circle stay untouched.getRenderPixeltranslates CSS pointer coordinates into backing-canvas pixels so loupe geometry stays accurate on Retina displays.- crossOrigin requests tiles with CORS headers enabled so browser security policies permit reading canvas pixel data.
Pitfalls
- Omitting crossOrigin (or pointing at a tile server that lacks Access-Control-Allow-Origin headers) taints the HTML5 canvas and causes
getImageDatato throw a DOM SecurityError. - Canvas resampling enlarges pixels already painted at the current zoom level rather than fetching deeper pyramid tiles—it aids visual legibility without adding sub-pixel sensor detail.
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.