Edit

Styling feature with CanvasGradient or CanvasPattern

canvas6 gradient1 pattern1 style26

Example showing a vector layer styled with a gradient.

This example creates a CanvasGradient. The vector data is loaded from a file and features are filled with the gradient. The same technique can be used with a CanvasPattern.

main.js
import KML from 'ol/format/KML.js';
import Map from 'ol/Map.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import View from 'ol/View.js';
import {DEVICE_PIXEL_RATIO} from 'ol/has.js';
import {Fill, Stroke, Style} from 'ol/style.js';
import {fromLonLat} from 'ol/proj.js';

// Gradient and pattern are in canvas pixel space, so we adjust for the
// renderer's pixel ratio
const pixelRatio = DEVICE_PIXEL_RATIO;

// Generate a rainbow gradient
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 1024 * pixelRatio, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1 / 6, 'orange');
gradient.addColorStop(2 / 6, 'yellow');
gradient.addColorStop(3 / 6, 'green');
gradient.addColorStop(4 / 6, 'aqua');
gradient.addColorStop(5 / 6, 'blue');
gradient.addColorStop(1, 'purple');

const vectorLayer = new VectorLayer({
  background: 'white',
  source: new VectorSource({
    url: 'data/kml/states.kml',
    format: new KML({extractStyles: false}),
  }),
  style: new Style({
    fill: new Fill({color: gradient}),
    stroke: new Stroke({
      color: '#333',
      width: 1,
    }),
  }),
});

const map = new Map({
  layers: [vectorLayer],
  target: 'map',
  view: new View({
    center: fromLonLat([-100, 38.5]),
    zoom: 4,
  }),
});
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Styling feature with CanvasGradient or CanvasPattern</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "canvas-gradient-pattern",
  "dependencies": {
    "ol": "10.2.1"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}