Edit

Styling feature with CanvasGradient or CanvasPattern

canvas6 gradient1 pattern1 style22

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 'ol/ol.css';
import KML from 'ol/format/KML';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {DEVICE_PIXEL_RATIO} from 'ol/has';
import {Fill, Stroke, Style} from 'ol/style';
import {fromLonLat} from 'ol/proj';

// 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>
    <!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
    <script src="https://unpkg.com/elm-pep@1.0.6/dist/elm-pep.js"></script>
    <!-- The lines below are only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,TextDecoder"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.18.3/minified.js"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "canvas-gradient-pattern",
  "dependencies": {
    "ol": "6.13.1-dev"
  },
  "devDependencies": {
    "parcel": "^2.0.0"
  },
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  }
}