Raster, GeoTIFF and WebGL · Angular, React and OpenLayers
NDVI computed in a raster source
Compute Sentinel-2 NDVI per pixel inside an OpenLayers RasterSource Web Worker using unnormalized GeoTIFFs, lib helpers and getData() lookup.

What this example shows
Over Kraków and surrounding fields at [resolution]="40" in UTM zone 34N, red and near-infrared Sentinel-2 GeoTIFF bands are combined pixel by pixel inside a background Web Worker to render an NDVI colour map in an image layer, with live two-decimal NDVI inspection (– outside data) on pointer move or click.
When you need it
When raster analysis requires custom JavaScript branching, lookup tables or third-party numerical functions that go beyond declarative WebGL style operators, OpenLayers’ Raster source executes arbitrary JavaScript per pixel inside worker threads.
Feeding unnormalized raw GeoTIFF bands into aol-source-raster gives worker functions exact physical reflectance values.
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.
cog-math-raster.shared.tsimport type { Coordinate } from 'ol/coordinate.js';
import type { SourceInfo } from 'ol/source/GeoTIFF.js';
const SCENE =
'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/34/U/DA/2024/8/S2B_34UDA_20240814_0_L2A';
/** The Main Market Square in the scene's projection, UTM zone 34N (EPSG:32634). */
export const KRAKOW: Coordinate = [423901, 5545999];
/** Red and near infrared, both at 10 m: the first two values of each pixel the operation gets. */
export const SOURCES: SourceInfo[] = [{ url: `${SCENE}/B04.tif` }, { url: `${SCENE}/B08.tif` }];
/** A value of the ramp and its colour. */
export type Stop = [number, [number, number, number]];
/** NDVI values from -0.2 to 0.65 and the colour of each, from grey through yellow to dark green. */
export const RAMP: Stop[] = [
[-0.2, [191, 191, 191]],
[-0.1, [219, 219, 219]],
[0, [255, 255, 224]],
[0.025, [255, 250, 204]],
[0.05, [237, 232, 181]],
[0.075, [222, 217, 156]],
[0.1, [204, 199, 130]],
[0.125, [189, 184, 107]],
[0.15, [176, 194, 97]],
[0.175, [163, 204, 89]],
[0.2, [145, 191, 82]],
[0.25, [128, 179, 71]],
[0.3, [112, 163, 64]],
[0.35, [97, 150, 54]],
[0.4, [79, 138, 46]],
[0.45, [64, 125, 36]],
[0.5, [48, 110, 28]],
[0.55, [33, 97, 18]],
[0.6, [15, 84, 10]],
[0.65, [0, 69, 0]],
];
/** What the operation gets from `beforeoperations`. */
export interface NdviData {
stops: Stop[];
}
/**
* The functions the raster worker defines under these names before it runs the operation, which calls them by
* these names as globals: a production build renames the functions of this module, and a name taken from the
* module would not exist in the worker.
*/
export const WORKER_LIB = {
/** The `[r, g, b, a]` colour of a value between the ramp's stops; the end colours outside them. */
colorFromRamp: (value: number, stops: Stop[]): number[] => {
if (value <= stops[0][0]) return [...stops[0][1], 255];
for (let i = 1; i < stops.length; i++) {
const [highValue, high] = stops[i];
if (value <= highValue) {
const [lowValue, low] = stops[i - 1];
const f = (value - lowValue) / (highValue - lowValue);
return [low[0] + f * (high[0] - low[0]), low[1] + f * (high[1] - low[1]), low[2] + f * (high[2] - low[2]), 255];
}
}
return [...stops[stops.length - 1][1], 255];
},
};
/* Defined in the raster worker from `WORKER_LIB`. */
declare const colorFromRamp: (typeof WORKER_LIB)['colorFromRamp'];
/** The NDVI of a pixel's red and near-infrared values as a colour of the ramp; transparent outside the data. */
export function ndviToColor(pixels: number[][], data: object): number[] {
const [red, nir] = pixels[0];
const sum = nir + red;
if (!sum) return [0, 0, 0, 0];
return colorFromRamp((nir - red) / sum, (data as NdviData).stops);
}cog-math-raster.tsimport { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import {
DefaultControlComponent,
DefaultInteractionComponent,
LayerImageComponent,
MapComponent,
SourceRasterComponent,
ViewComponent,
} from 'cc-openlayers';
import { SourceGeoTIFFComponent } from 'cc-openlayers/webgl';
import type { MapBrowserEvent } from 'ol';
import type { ViewOptions } from 'ol/View';
import type { RasterSourceEvent } from 'ol/source/Raster';
import { KRAKOW, type NdviData, ndviToColor, RAMP, SOURCES, WORKER_LIB } from './cog-math-raster.shared';
/**
* NDVI from the red and near-infrared bands of a Sentinel-2 scene over Kraków, calculated per pixel in a worker by
* a raster source from the raw values of a GeoTIFF source; the values under the pointer are read back from it.
*/
@Component({
selector: 'app-cog-math-raster',
imports: [
DefaultControlComponent,
DefaultInteractionComponent,
LayerImageComponent,
MapComponent,
SourceGeoTIFFComponent,
SourceRasterComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px" (pointerMove)="showNdvi($event)" (singleClick)="showNdvi($event)">
<aol-interaction-default />
<aol-control-defaults />
@if (view(); as options) {
<aol-view
[projection]="options.projection"
[resolutions]="options.resolutions"
[extent]="options.extent"
[center]="krakow"
[resolution]="40"
/>
}
<aol-layer-image>
<aol-source-raster [operation]="operation" [lib]="lib" (beforeOperations)="beforeOperations($event)">
<aol-source-geotiff
[sources]="sources"
[normalize]="false"
attributions="Contains modified Copernicus Sentinel data 2024"
(viewReady)="view.set($event)"
/>
</aol-source-raster>
</aol-layer-image>
</aol-map>
<div class="example-controls">
<span>
NDVI <output>{{ ndvi() }}</output>
</span>
</div>
`,
})
export class CogMathRaster {
readonly view = signal<ViewOptions | undefined>(undefined);
protected readonly krakow = KRAKOW;
protected readonly operation = ndviToColor;
protected readonly lib = WORKER_LIB;
protected readonly raster = viewChild.required(SourceRasterComponent);
protected readonly value = signal<string | undefined>(undefined);
protected readonly ndvi = computed(() => this.value() ?? '–');
protected readonly sources = SOURCES;
/** Hands the ramp to the operation. */
protected beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
const data: NdviData = event.data;
data.stops = RAMP;
}
/** Calculates the NDVI of the raw values under the pointer or a click; none outside the data. */
protected showNdvi(event: MapBrowserEvent): void {
const [red, nir] = this.raster().instance.getData(event.coordinate)?.[0] ?? [0, 0];
const sum = nir + red;
this.value.set(sum ? ((nir - red) / sum).toFixed(2) : undefined);
}
} 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.
cog-math-raster.react.tsximport { useCallback, useState } from 'react';
import type { MapBrowserEvent } from 'ol';
import type Raster from 'ol/source/Raster.js';
import type { Operation, RasterSourceEvent } from 'ol/source/Raster.js';
import type { ViewOptions } from 'ol/View.js';
import { DefaultControls, DefaultInteractions, ImageLayer, Map, RasterSource, View } from 'cc-openlayers/react';
import { GeoTIFFSource } from 'cc-openlayers/react/webgl';
import { KRAKOW, type NdviData, ndviToColor, RAMP, SOURCES, WORKER_LIB } from './cog-math-raster.shared';
/** Hands the ramp to the operation. */
function beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
const data: NdviData = event.data;
data.stops = RAMP;
}
/**
* NDVI from the red and near-infrared bands of a Sentinel-2 scene over Kraków, calculated per pixel in a worker by
* a raster source from the raw values of a GeoTIFF source; the values under the pointer are read back from it.
*/
export function CogMathRaster() {
const [view, setView] = useState<ViewOptions | undefined>(undefined);
const [raster, setRaster] = useState<Raster | null>(null);
const [value, setValue] = useState<string | undefined>(undefined);
const ndvi = value ?? '–';
/** Calculates the NDVI of the raw values under the pointer or a click; none outside the data. */
const showNdvi = useCallback(
(event: MapBrowserEvent) => {
const [red, nir] = raster?.getData(event.coordinate)?.[0] ?? [0, 0];
const sum = nir + red;
setValue(sum ? ((nir - red) / sum).toFixed(2) : undefined);
},
[raster]
);
return (
<>
<Map height="480px" onPointerMove={showNdvi} onSingleClick={showNdvi}>
<DefaultInteractions />
<DefaultControls />
{view && (
<View
projection={view.projection}
resolutions={view.resolutions}
extent={view.extent}
center={KRAKOW}
resolution={40}
/>
)}
<ImageLayer>
<RasterSource
ref={setRaster}
operation={ndviToColor as Operation}
lib={WORKER_LIB}
onBeforeOperations={beforeOperations}
>
<GeoTIFFSource
sources={SOURCES}
normalize={false}
attributions="Contains modified Copernicus Sentinel data 2024"
onViewReady={setView}
/>
</RasterSource>
</ImageLayer>
</Map>
<div className="example-controls">
<span>
NDVI <output>{ndvi}</output>
</span>
</div>
</>
);
}cog-math-raster.shared.tsimport type { Coordinate } from 'ol/coordinate.js';
import type { SourceInfo } from 'ol/source/GeoTIFF.js';
const SCENE =
'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/34/U/DA/2024/8/S2B_34UDA_20240814_0_L2A';
/** The Main Market Square in the scene's projection, UTM zone 34N (EPSG:32634). */
export const KRAKOW: Coordinate = [423901, 5545999];
/** Red and near infrared, both at 10 m: the first two values of each pixel the operation gets. */
export const SOURCES: SourceInfo[] = [{ url: `${SCENE}/B04.tif` }, { url: `${SCENE}/B08.tif` }];
/** A value of the ramp and its colour. */
export type Stop = [number, [number, number, number]];
/** NDVI values from -0.2 to 0.65 and the colour of each, from grey through yellow to dark green. */
export const RAMP: Stop[] = [
[-0.2, [191, 191, 191]],
[-0.1, [219, 219, 219]],
[0, [255, 255, 224]],
[0.025, [255, 250, 204]],
[0.05, [237, 232, 181]],
[0.075, [222, 217, 156]],
[0.1, [204, 199, 130]],
[0.125, [189, 184, 107]],
[0.15, [176, 194, 97]],
[0.175, [163, 204, 89]],
[0.2, [145, 191, 82]],
[0.25, [128, 179, 71]],
[0.3, [112, 163, 64]],
[0.35, [97, 150, 54]],
[0.4, [79, 138, 46]],
[0.45, [64, 125, 36]],
[0.5, [48, 110, 28]],
[0.55, [33, 97, 18]],
[0.6, [15, 84, 10]],
[0.65, [0, 69, 0]],
];
/** What the operation gets from `beforeoperations`. */
export interface NdviData {
stops: Stop[];
}
/**
* The functions the raster worker defines under these names before it runs the operation, which calls them by
* these names as globals: a production build renames the functions of this module, and a name taken from the
* module would not exist in the worker.
*/
export const WORKER_LIB = {
/** The `[r, g, b, a]` colour of a value between the ramp's stops; the end colours outside them. */
colorFromRamp: (value: number, stops: Stop[]): number[] => {
if (value <= stops[0][0]) return [...stops[0][1], 255];
for (let i = 1; i < stops.length; i++) {
const [highValue, high] = stops[i];
if (value <= highValue) {
const [lowValue, low] = stops[i - 1];
const f = (value - lowValue) / (highValue - lowValue);
return [low[0] + f * (high[0] - low[0]), low[1] + f * (high[1] - low[1]), low[2] + f * (high[2] - low[2]), 255];
}
}
return [...stops[stops.length - 1][1], 255];
},
};
/* Defined in the raster worker from `WORKER_LIB`. */
declare const colorFromRamp: (typeof WORKER_LIB)['colorFromRamp'];
/** The NDVI of a pixel's red and near-infrared values as a colour of the ramp; transparent outside the data. */
export function ndviToColor(pixels: number[][], data: object): number[] {
const [red, nir] = pixels[0];
const sum = nir + red;
if (!sum) return [0, 0, 0, 0];
return colorFromRamp((nir - red) / sum, (data as NdviData).stops);
}How the React version works
The NDVI of a Sentinel-2 scene over Kraków calculated per pixel by a raster source in a worker and coloured along a ramp; the value under the pointer or a click is shown below the map. The source reads the file in the browser, so nothing is drawn before its metadata arrive.
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 import the centre over Kraków, the sources, the ramp, the worker library and ndviToColor from the example's .shared.ts file, so the logic exists once. The raster source turns the operation into source text for its worker.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-image> with <aol-source-raster [operation] [lib]> around <aol-source-geotiff> | <ImageLayer> with <RasterSource operation lib> around <GeoTIFFSource> |
(viewReady) and a signal of the view options | onViewReady and useState; the View is rendered once the options are there |
viewChild of the raster source and its pixel data | ref={setRaster} into useState, read in the pointer and click handlers |
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
aol-layer-image wraps aol-source-raster, which takes an aol-source-geotiff (B04.tif and B08.tif with [normalize]="false") as its input. Because worker threads run in an isolated scope serialized from function source text, helper colorFromRamp is injected via [lib]="lib" and the colour RAMP array is attached per frame on (beforeOperations).
Worker function ndviToColor computes (nir - red) / (nir + red) (leaving pixels transparent when nir + red === 0), while showNdvi reads raw input tuple values on the main thread via this.raster().instance.getData(event.coordinate)?.[0].
How it works
aol-source-rasterconsumes anaol-source-geotiffofB04.tifandB08.tifconfigured with[normalize]="false"for raw reflectance values.ndviToColorevaluates per-pixel NDVI in a worker usingcolorFromRampsupplied through[lib]="lib", keeping zero-sum pixels transparent.beforeOperationscopiesRAMPintoevent.dataahead of each worker pass.showNdviinspectsthis.raster().instance.getData(event.coordinate)?.[0]on pointer moves and clicks to display live NDVI.
Pitfalls
- Functions serialized into a Raster worker cannot close over outer module imports or component fields—every helper function must be passed in
liband every runtime parameter inbeforeOperationsevent.data. - CPU worker operations recompute the entire viewport after each settled pan or zoom; prefer GPU WebGL style expressions (
cog-math) whenever standard band arithmetic suffices.
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.