Styling and labels · Angular, React and OpenLayers

A gradient fill in canvas pixels

Fill Polish voivodeship polygons with a device-pixel-scaled HTML5 CanvasGradient in an OpenLayers Fill style over a clean white layer background.

Poland's voivodeships outlined in grey on white, filled with the cool end of a rainbow gradient: aqua in the west, blue in the middle and purple in the east.
A screenshot of the example. Voivodeships: Państwowy Rejestr Granic © GUGiK.

What this example shows

Across a basemap-free white canvas (background="white"), Poland’s 16 voivodeship polygons are outlined in grey and filled with a continuous horizontal rainbow CanvasGradient transitioning smoothly from aqua in western Poland through blue around Kraków to purple in the east.

When you need it

Cartographic fills often require richer visuals than flat RGBA colours—such as diagonal hatching for restricted planning zones, repeating marshland stipple patterns or continuous directional gradients.

Because OpenLayers’ Fill color property natively accepts standard HTML5 CanvasGradient and CanvasPattern instances, custom fills plug directly into normal vector styles.

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.

canvas-gradient-pattern.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerVectorComponent,
  MapComponent,
  SourceGeoJSONComponent,
  ViewComponent,
} from 'cc-openlayers';
import { DEVICE_PIXEL_RATIO } from 'ol/has';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';

/** Poland's voivodeships filled with a CanvasGradient: a rainbow in canvas pixel space. */
@Component({
  selector: 'app-canvas-gradient-pattern',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerVectorComponent,
    MapComponent,
    SourceGeoJSONComponent,
    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="white" [style]="style">
        <aol-source-geojson url="assets/poland/voivodeships.geojson" featureProjection="EPSG:3857" />
      </aol-layer-vector>
    </aol-map>
  `,
})
export class CanvasGradientPattern {
  protected readonly style = new Style({
    fill: new Fill({ color: rainbow() }),
    stroke: new Stroke({ color: '#333', width: 1 }),
  });
}

/** A gradient and a pattern are in canvas pixel space, so the width is scaled by the renderer's pixel ratio. */
function rainbow(): CanvasGradient {
  const context = document.createElement('canvas').getContext('2d');
  if (!context) throw new Error('A 2D canvas context is required');
  const gradient = context.createLinearGradient(0, 0, 1024 * DEVICE_PIXEL_RATIO, 0);
  ['red', 'orange', 'yellow', 'green', 'aqua', 'blue', 'purple'].forEach((color, index) =>
    gradient.addColorStop(index / 6, color)
  );
  return gradient;
}

Architecture and OpenLayers mechanics

An off-screen 2D canvas context creates createLinearGradient(0, 0, 1024 * DEVICE_PIXEL_RATIO, 0)—multiplying CSS pixel span by screen pixel density because OpenLayers paints vector layers in physical device pixels—and passes that gradient as the color of one shared Fill used across all 16 voivodeships.

During pans, OpenLayers anchors canvas gradients and repeating patterns to a 512-pixel world-aligned grid so seamlessly tiled patterns (8, 16, 32, 64 px) stay geographically locked inside moving polygons.

How it works

  • createLinearGradient(0, 0, 1024 * DEVICE_PIXEL_RATIO, 0) scales the rainbow ramp in physical device pixels to match high-density displays.
  • Passing the CanvasGradient directly as color on a standard Fill lets one style instance render every voivodeship.
  • background="white" fills empty space around Poland cleanly without needing a base tile layer.
  • OpenLayers steps pattern/gradient origins in 512-pixel increments so repeating hatch tiles dividing 512 px stay locked to features while panning.

Pitfalls

  • Because OpenLayers resets fill origins every 512 pixels during pans, a non-repeating gradient wider than 512 pixels (such as 1024 px here) shifts across features and steps back every 512 pixels of drag—use widths/tiles that divide 512 evenly when fills must stay stationary.
  • Forgetting DEVICE_PIXEL_RATIO compresses a CSS-pixel gradient to half its intended width on 2x Retina screens.

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.