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.

The orthophotomap of central Kraków at zoom 13 with the Main Square at twice its size inside a white ring around the pointer.
A screenshot of the example. Orthophotomap © GUGiK.

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

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], getImageData reads rendered pixels around the cursor and remaps each interior pixel from halfway to the centre for 2x magnification.
  • putImageData writes the resampled pixel square back inside a block opened by save() and closed by restore(), which then strokes the white ring; pixels outside the circle stay untouched.
  • getRenderPixel translates 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 getImageData to 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.

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.