Atlaslog
Atlaslog / Examples / OpenLayers / Cog Math Multisource
OpenLayers · Runnable Example

Cog Math Multisource

Runnable OpenLayers example: Cog Math Multisource. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-cog-math-multisource.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-cog-math-multisource.html
<!--
  示例:多源栅格数学运算
  要点:一个 ol.source.Raster 挂多个输入源,按波段做归一化植被指数
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>多源栅格数学运算</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#16181d}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:12px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label><input type="radio" name="view" value="ndvi" checked> 植被指数</label>
  <label><input type="radio" name="view" value="red"> 红光波段</label>
  <label><input type="radio" name="view" value="nir"> 近红外波段</label>
  <span id="legend">NDVI = (近红外 − 红光) / (近红外 + 红光)</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';
  if (!window.ol) {
    document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查 cdn.jsdelivr.net 是否可访问';
    return;
  }

  var SIZE = 256;
  var extent = ol.proj.transformExtent([116.20, 39.75, 116.62, 40.05], 'EPSG:4326', 'EPSG:3857');

  /* 两个“波段”:红光低、近红外高表示植被茂盛,两者用互补的纹理 */
  function bandURL(kind) {
    var c = document.createElement('canvas');
    c.width = c.height = SIZE;
    var ctx = c.getContext('2d');
    var img = ctx.createImageData(SIZE, SIZE);
    for (var y = 0; y < SIZE; y++) {
      for (var x = 0; x < SIZE; x++) {
        var u = x / SIZE, v = y / SIZE;
        var veg = 0.5 + 0.35 * Math.sin(u * 5.2) * Math.cos(v * 4.4) + 0.12 * Math.sin((u - v) * 13.5);
        veg = Math.max(0, Math.min(1, veg));
        var val = kind === 'nir' ? veg : 1 - veg * 0.85;
        var i = (y * SIZE + x) * 4;
        img.data[i] = Math.round(val * 255);
        img.data[i + 1] = Math.round((kind === 'nir' ? val * 0.92 : val * 0.7) * 255);
        img.data[i + 2] = Math.round((kind === 'nir' ? val * 0.85 : val * 0.55) * 255);
        img.data[i + 3] = 255;
      }
    }
    ctx.putImageData(img, 0, 0);
    return c.toDataURL('image/png');
  }

  var redURL = bandURL('red');
  var nirURL = bandURL('nir');

  function staticSource(url) {
    return new ol.source.ImageStatic({ url: url, imageExtent: extent, projection: 'EPSG:3857' });
  }

  function ramp(t) {
    var stops = [[0, 120, 44, 40], [0.4, 214, 190, 110], [0.55, 140, 190, 92], [0.75, 46, 138, 62], [1, 12, 78, 42]];
    for (var i = 0; i < stops.length - 1; i++) {
      if (t >= stops[i][0] && t <= stops[i + 1][0]) {
        var f = (t - stops[i][0]) / (stops[i + 1][0] - stops[i][0]);
        return [
          stops[i][1] + (stops[i + 1][1] - stops[i][1]) * f,
          stops[i][2] + (stops[i + 1][2] - stops[i][2]) * f,
          stops[i][3] + (stops[i + 1][3] - stops[i][3]) * f
        ];
      }
    }
    return [12, 78, 42];
  }

  var mode = 'ndvi';
  var layer;

  function build() {
    var raster = new ol.source.Raster({
      sources: [staticSource(redURL), staticSource(nirURL)],
      operation: function (pixels) {
        var red = pixels[0], nir = pixels[1];
        var out = new ImageData(red.width, red.height);
        for (var i = 0; i < red.data.length; i += 4) {
          var r = red.data[i] / 255, n = nir.data[i] / 255;
          var rr, gg, bb;
          if (mode === 'ndvi') {
            var ndvi = (n - r) / Math.max(1e-6, n + r);
            var c = ramp(Math.max(0, Math.min(1, (ndvi + 1) / 2)));
            rr = c[0]; gg = c[1]; bb = c[2];
          } else {
            var v = (mode === 'nir' ? n : r) * 255;
            rr = gg = bb = v;
          }
          out.data[i] = rr; out.data[i + 1] = gg; out.data[i + 2] = bb; out.data[i + 3] = 255;
        }
        return out;
      }
    });
    return new ol.layer.Image({ source: raster, opacity: 0.88 });
  }

  var map = new ol.Map({
    target: 'map',
    layers: [new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) })],
    view: new ol.View({ center: ol.proj.fromLonLat([116.40, 39.90]), zoom: 10 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  layer = build();
  map.addLayer(layer);

  document.querySelectorAll('input[name=view]').forEach(function (el) {
    el.addEventListener('change', function () {
      mode = this.value;
      map.removeLayer(layer);
      layer = build();
      map.addLayer(layer);
    });
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLECog Modeltransformation OpenLayers · EXAMPLECog Overviews OpenLayers · EXAMPLECog Projection