Raster, GeoTIFF and WebGL · Angular, React and OpenLayers
Shaded relief computed on the GPU
Compute interactive GPU hillshade relief in OpenLayers WebGLTileLayer by sampling neighbouring Terrarium elevation pixels inside shaders.

What this example shows
West of Kraków over the wooded hills of Las Wolski, Kopiec Piłsudskiego and the Vistula river bend at zoom 13, analytical shaded relief ([opacity]="0.3") renders directly on the GPU over OpenStreetMap—responding instantaneously without worker delay as you drag sliders for vertical exaggeration, sun elevation and sun azimuth (starting at 1×, 45° and 45°).
When you need it
GPU fragment-shader hillshading delivers zero-latency interactive terrain lighting during fast pans, continuous pinch-zooms and live sun-angle scrubbing where CPU ImageData workers lag on high-DPI screens.
OpenLayers’ 4-argument band operator lets WebGL expressions sample neighbouring pixels directly inside declarative style JSON without writing raw GLSL.
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.
webgl-shaded-relief.shared.tsimport type { ExpressionValue } from 'ol/expr/expression.js';
import type { Style } from 'ol/layer/WebGLTile.js';
export type Setting = 'vert' | 'sunEl' | 'sunAz';
// The method used to extract elevations from the DEM.
// In this case the format used is Terrarium
// red * 256 + green + blue / 256 - 32768
//
// Other frequently used methods include the Mapbox format
// (red * 256 * 256 + green * 256 + blue) * 0.1 - 10000
//
export function elevation(xOffset: number, yOffset: number): ExpressionValue {
const red = ['band', 1, xOffset, yOffset];
const green = ['band', 2, xOffset, yOffset];
const blue = ['band', 3, xOffset, yOffset];
// band math operates on normalized values from 0-1
// so we scale by 255
return ['+', ['*', 255 * 256, red], ['*', 255, green], ['*', 255 / 256, blue], -32768];
}
// Generates a shaded relief image given elevation data. Uses a 3x3
// neighborhood for determining slope and aspect.
export const dp = ['*', 2, ['resolution']];
export const z0x = ['*', ['var', 'vert'], elevation(-1, 0)];
export const z1x = ['*', ['var', 'vert'], elevation(1, 0)];
export const dzdx = ['/', ['-', z1x, z0x], dp];
export const z0y = ['*', ['var', 'vert'], elevation(0, -1)];
export const z1y = ['*', ['var', 'vert'], elevation(0, 1)];
export const dzdy = ['/', ['-', z1y, z0y], dp];
export const slope = ['atan', ['sqrt', ['+', ['^', dzdx, 2], ['^', dzdy, 2]]]];
export const aspect = ['clamp', ['atan', ['-', 0, dzdx], dzdy], -Math.PI, Math.PI];
export const sunEl = ['*', Math.PI / 180, ['var', 'sunEl']];
export const sunAz = ['*', Math.PI / 180, ['var', 'sunAz']];
export const cosIncidence = [
'+',
['*', ['sin', sunEl], ['cos', slope]],
['*', ['cos', sunEl], ['sin', slope], ['cos', ['-', sunAz, aspect]]],
];
export const scaled = ['*', 255, cosIncidence];
export const STYLE: Style = { color: ['color', scaled] };
export const CONTROLS: { id: Setting; label: string; min: number; max: number; unit: string }[] = [
{ id: 'vert', label: 'vertical exaggeration:', min: 1, max: 5, unit: 'x' },
{ id: 'sunEl', label: 'sun elevation:', min: 0, max: 90, unit: '°' },
{ id: 'sunAz', label: 'sun azimuth:', min: 0, max: 360, unit: '°' },
];webgl-shaded-relief.tsimport { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
MapComponent,
SourceImageTileComponent,
SourceOsmComponent,
ViewComponent,
} from 'cc-openlayers';
import { LayerWebGLTileComponent } from 'cc-openlayers/webgl';
import { CONTROLS, type Setting, STYLE } from './webgl-shaded-relief.shared';
/**
* A shaded relief of the hills of Las Wolski west of Kraków, computed on the GPU from Terrarium elevation tiles over
* OpenStreetMap: the layer's `color` expression samples each pixel's neighbours for slope and aspect, and the sliders
* update the style variables for the vertical exaggeration and the sun's elevation and azimuth.
*/
@Component({
selector: 'app-webgl-shaded-relief',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
LayerTileComponent,
LayerWebGLTileComponent,
MapComponent,
SourceImageTileComponent,
SourceOsmComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="13">
<aol-coordinate [x]="19.86" [y]="50.055" srid="EPSG:4326" />
</aol-view>
<aol-layer-tile><aol-source-osm /></aol-layer-tile>
<aol-layer-webgltile [opacity]="0.3" [style]="style" [variables]="variables()">
<aol-source-imagetile
url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
[maxZoom]="15"
attributions='<a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Data sources and attribution</a>'
/>
</aol-layer-webgltile>
</aol-map>
<div class="example-controls">
@for (control of controls; track control.id) {
<label>
{{ control.label }}
<input
type="range"
[name]="control.id"
[min]="control.min"
[max]="control.max"
[value]="variables()[control.id]"
(input)="set(control.id, $event)"
/>
<output>{{ variables()[control.id] }} {{ control.unit }}</output>
</label>
}
</div>
`,
})
export class WebglShadedRelief {
readonly variables = signal<Record<Setting, number>>({ vert: 1, sunEl: 45, sunAz: 45 });
protected readonly style = STYLE;
protected readonly controls = CONTROLS;
protected set(setting: Setting, event: Event): void {
const value = Number((event.target as HTMLInputElement).value);
this.variables.update((variables) => ({ ...variables, [setting]: value }));
}
} 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.
webgl-shaded-relief.react.tsximport { useState, type ChangeEvent } from 'react';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageTileSource,
Map,
OSMSource,
TileLayer,
View,
} from 'cc-openlayers/react';
import { WebGLTileLayer } from 'cc-openlayers/react/webgl';
import { CONTROLS, type Setting, STYLE } from './webgl-shaded-relief.shared';
/**
* A shaded relief of the hills of Las Wolski west of Kraków, computed on the GPU from Terrarium elevation tiles over
* OpenStreetMap: the layer's `color` expression samples each pixel's neighbours for slope and aspect, and the sliders
* update the style variables for the vertical exaggeration and the sun's elevation and azimuth.
*/
export function WebglShadedRelief() {
const [variables, setVariables] = useState<Record<Setting, number>>({ vert: 1, sunEl: 45, sunAz: 45 });
const set = (setting: Setting, event: ChangeEvent<HTMLInputElement>) => {
const value = Number(event.target.value);
setVariables((current) => ({ ...current, [setting]: value }));
};
return (
<>
<Map height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={13}>
<Coordinate x={19.86} y={50.055} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<WebGLTileLayer opacity={0.3} style={STYLE} variables={variables}>
<ImageTileSource
url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
maxZoom={15}
attributions='<a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Data sources and attribution</a>'
/>
</WebGLTileLayer>
</Map>
<div className="example-controls">
{CONTROLS.map((control) => (
<label key={control.id}>
{control.label}
<input
type="range"
name={control.id}
min={control.min}
max={control.max}
value={variables[control.id]}
onChange={(event) => set(control.id, event)}
/>
<output>
{variables[control.id]} {control.unit}
</output>
</label>
))}
</div>
</>
);
}webgl-shaded-relief.shared.tsimport type { ExpressionValue } from 'ol/expr/expression.js';
import type { Style } from 'ol/layer/WebGLTile.js';
export type Setting = 'vert' | 'sunEl' | 'sunAz';
// The method used to extract elevations from the DEM.
// In this case the format used is Terrarium
// red * 256 + green + blue / 256 - 32768
//
// Other frequently used methods include the Mapbox format
// (red * 256 * 256 + green * 256 + blue) * 0.1 - 10000
//
export function elevation(xOffset: number, yOffset: number): ExpressionValue {
const red = ['band', 1, xOffset, yOffset];
const green = ['band', 2, xOffset, yOffset];
const blue = ['band', 3, xOffset, yOffset];
// band math operates on normalized values from 0-1
// so we scale by 255
return ['+', ['*', 255 * 256, red], ['*', 255, green], ['*', 255 / 256, blue], -32768];
}
// Generates a shaded relief image given elevation data. Uses a 3x3
// neighborhood for determining slope and aspect.
export const dp = ['*', 2, ['resolution']];
export const z0x = ['*', ['var', 'vert'], elevation(-1, 0)];
export const z1x = ['*', ['var', 'vert'], elevation(1, 0)];
export const dzdx = ['/', ['-', z1x, z0x], dp];
export const z0y = ['*', ['var', 'vert'], elevation(0, -1)];
export const z1y = ['*', ['var', 'vert'], elevation(0, 1)];
export const dzdy = ['/', ['-', z1y, z0y], dp];
export const slope = ['atan', ['sqrt', ['+', ['^', dzdx, 2], ['^', dzdy, 2]]]];
export const aspect = ['clamp', ['atan', ['-', 0, dzdx], dzdy], -Math.PI, Math.PI];
export const sunEl = ['*', Math.PI / 180, ['var', 'sunEl']];
export const sunAz = ['*', Math.PI / 180, ['var', 'sunAz']];
export const cosIncidence = [
'+',
['*', ['sin', sunEl], ['cos', slope]],
['*', ['cos', sunEl], ['sin', slope], ['cos', ['-', sunAz, aspect]]],
];
export const scaled = ['*', 255, cosIncidence];
export const STYLE: Style = { color: ['color', scaled] };
export const CONTROLS: { id: Setting; label: string; min: number; max: number; unit: string }[] = [
{ id: 'vert', label: 'vertical exaggeration:', min: 1, max: 5, unit: 'x' },
{ id: 'sunEl', label: 'sun elevation:', min: 0, max: 90, unit: '°' },
{ id: 'sunAz', label: 'sun azimuth:', min: 0, max: 360, unit: '°' },
];How the React version works
A shaded relief of the hills of Las Wolski computed on the GPU from Terrarium elevation tiles over OpenStreetMap; sliders set the vertical exaggeration and the sun's elevation and azimuth.
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. OpenLayers draws the tiles with WebGL; the style expressions run on the GPU in both versions. Both versions import the shading expressions, the style and the controls from the example's .shared.ts file, so the logic exists once.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-webgltile [style] [variables]> | <WebGLTileLayer style variables> |
the sliders and a signal of the values | useState of the values |
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
Helper elevation(xOffset, yOffset) decodes Terrarium heights at integer pixel offsets (-1, 0), (+1, 0), (0, -1) and (0, +1) using ['band', 1, xOffset, yOffset] (and bands 2 and 3). Finite-difference gradients dzdx and dzdy multiply height differences by ['var', 'vert'] divided by dp (twice the built-in resolution), deriving slope, aspect and solar incidence scaled (0..255) inside { color: ['color', scaled] }.
[variables]="variables()" streams vert, sunEl and sunAz directly to shader uniforms.
How it works
- The WebGL style outputs
{ color: ['color', scaled] }wherescaledscales the cosine of solar incidence onto 0..255. elevationsamples neighbouring pixels via['band', 1, xOffset, yOffset](and bands 2–3) to decode local heights on the GPU.dzdxanddzdydivide['var', 'vert']-scaled height differences bydp(twice the built-in resolution) to compute terrain slope and aspect.[variables]="variables()"updatesvert,sunElandsunAz(initialised to1,45,45) at[opacity]="0.3"over OpenStreetMap.
Pitfalls
- Built-in
['resolution']reports Web Mercator projection units per pixel, making raw gradients ~0.64× as steep as true ground metres at Kraków’s 50° N latitude unless compensated invert. - Always keep the complex hillshade expression static in
[style]and pass slider values via[variables]so dragging sun sliders never triggers expensive shader recompilation.
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.