Atlaslog
Atlaslog / Examples / OpenLayers / Cog Colors
OpenLayers · Runnable Example

Cog Colors

Runnable OpenLayers example: Cog Colors. 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-colors.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-cog-colors.html
<!--
  示例:栅格颜色表映射
  要点:ol.source.Raster 的 operation 按色带把单波段灰度映射成彩色
  依赖: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}
  .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="ramp" value="terrain" checked> 地形色带</label>
  <label><input type="radio" name="ramp" value="viridis"> 紫绿色带</label>
  <label><input type="radio" name="ramp" value="gray"> 灰度</label>
</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');

  /* 单波段“高程”数据:用几组正弦叠加生成起伏,写进画布再转成 dataURL */
  function fieldURL() {
    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 h = 0.5
          + 0.28 * Math.sin(u * 6.1 + 0.6) * Math.cos(v * 5.3)
          + 0.14 * Math.sin((u + v) * 11.7)
          + 0.08 * Math.cos(u * 23.0 - v * 17.0);
        h = Math.max(0, Math.min(1, h));
        var i = (y * SIZE + x) * 4;
        var g = Math.round(h * 255);
        img.data[i] = img.data[i + 1] = img.data[i + 2] = g;
        img.data[i + 3] = 255;
      }
    }
    ctx.putImageData(img, 0, 0);
    return c.toDataURL('image/png');
  }

  var url = fieldURL();

  var ramps = {
    terrain: [[0, '#0b3d91'], [0.25, '#2f9e6e'], [0.45, '#a8c95a'], [0.65, '#e0c060'], [0.82, '#a8703f'], [1, '#f6f2ea']],
    viridis: [[0, '#440154'], [0.25, '#3b528b'], [0.5, '#21918c'], [0.75, '#5ec962'], [1, '#fde725']],
    gray:    [[0, '#101114'], [1, '#f2f2f2']]
  };

  function makeLookup(name) {
    var stops = ramps[name];
    var lut = new Uint8ClampedArray(256 * 3);
    for (var v = 0; v < 256; v++) {
      var t = v / 255;
      var a = stops[0], b = stops[stops.length - 1];
      for (var s = 0; s < stops.length - 1; s++) {
        if (t >= stops[s][0] && t <= stops[s + 1][0]) { a = stops[s]; b = stops[s + 1]; break; }
      }
      var f = (t - a[0]) / Math.max(1e-6, b[0] - a[0]);
      var ca = parseHex(a[1]), cb = parseHex(b[1]);
      lut[v * 3] = ca[0] + (cb[0] - ca[0]) * f;
      lut[v * 3 + 1] = ca[1] + (cb[1] - ca[1]) * f;
      lut[v * 3 + 2] = ca[2] + (cb[2] - ca[2]) * f;
    }
    return lut;
  }

  function parseHex(hex) {
    return [parseInt(hex.substr(1, 2), 16), parseInt(hex.substr(3, 2), 16), parseInt(hex.substr(5, 2), 16)];
  }

  function buildLayer(rampName) {
    var lut = makeLookup(rampName);
    var base = new ol.source.ImageStatic({
      url: url,
      imageExtent: extent,
      projection: 'EPSG:3857'
    });

    var raster = new ol.source.Raster({
      sources: [base],
      operation: function (pixels) {
        var input = pixels[0];
        var out = new ImageData(input.width, input.height);
        for (var i = 0; i < input.data.length; i += 4) {
          var v = input.data[i];
          out.data[i] = lut[v * 3];
          out.data[i + 1] = lut[v * 3 + 1];
          out.data[i + 2] = lut[v * 3 + 2];
          out.data[i + 3] = 255;
        }
        return out;
      }
    });

    return new ol.layer.Image({ source: raster, opacity: 0.9 });
  }

  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 })
  });

  var current = buildLayer('terrain');
  map.addLayer(current);

  document.querySelectorAll('input[name=ramp]').forEach(function (el) {
    el.addEventListener('change', function () {
      map.removeLayer(current);
      current = buildLayer(this.value);
      map.addLayer(current);
    });
  });
})();
</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 Custom Client OpenLayers · EXAMPLECog Math OpenLayers · EXAMPLECog Math Multisource