Atlaslog
Atlaslog / Examples / OpenLayers / Contour Interpolation
OpenLayers · Runnable Example

Contour Interpolation

Runnable OpenLayers example: Contour Interpolation. 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-contour-interpolation.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-contour-interpolation.html
<!--
  示例:DEM 等高线渲染 — OpenLayers contour-interpolation
  核心逻辑: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>DEM 等高线渲染</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}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:6px;align-items:center}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label>等高距 <input type="range" id="step" min="20" max="200" step="10" value="80"><b id="stepVal">80 m</b></label>
  <label><input type="checkbox" id="tgl" checked> 高程渲染</label>
  <span id="info">—</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 (typeof ol === 'undefined') {
    document.getElementById('map').innerHTML =
      '<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var MAX_ELEV = 2200;

  /* 用多个高斯山体叠出一幅 512 × 512 的高程栅格,灰度存高度 */
  function makeDem() {
    var size = 512;
    var c = document.createElement('canvas');
    c.width = size;
    c.height = size;
    var ctx = c.getContext('2d');
    var img = ctx.createImageData(size, size);

    var peaks = [
      { x: 0.32, y: 0.38, h: 1.0, s: 0.16 },
      { x: 0.62, y: 0.30, h: 0.78, s: 0.13 },
      { x: 0.55, y: 0.66, h: 0.62, s: 0.11 },
      { x: 0.78, y: 0.72, h: 0.45, s: 0.09 }
    ];

    for (var y = 0; y < size; y++) {
      for (var x = 0; x < size; x++) {
        var nx = x / size, ny = y / size;
        var elev = 0.12;
        peaks.forEach(function (p) {
          var dx = nx - p.x, dy = ny - p.y;
          elev += p.h * Math.exp(-(dx * dx + dy * dy) / (2 * p.s * p.s));
        });
        elev = Math.max(0, Math.min(1, elev));
        var v = Math.round(elev * 255);
        var i = (y * size + x) * 4;
        img.data[i] = v;
        img.data[i + 1] = v;
        img.data[i + 2] = v;
        img.data[i + 3] = 255;
      }
    }
    ctx.putImageData(img, 0, 0);
    return c.toDataURL();
  }

  var extent = ol.proj.transformExtent(
    [116.05, 39.72, 116.70, 40.12], 'EPSG:4326', 'EPSG:3857'
  );

  var demSource = new ol.source.ImageStatic({
    url: makeDem(),
    projection: 'EPSG:3857',
    imageExtent: extent,
    crossOrigin: 'anonymous'
  });

  /* 高程色带 */
  var STOPS = [
    [0.00, 50, 92, 66],
    [0.28, 118, 158, 88],
    [0.52, 206, 189, 120],
    [0.74, 168, 124, 82],
    [1.00, 245, 245, 245]
  ];

  function ramp(t) {
    for (var i = 1; i < STOPS.length; i++) {
      if (t <= STOPS[i][0]) {
        var a = STOPS[i - 1], b = STOPS[i];
        var k = (t - a[0]) / (b[0] - a[0]);
        return [
          Math.round(a[1] + (b[1] - a[1]) * k),
          Math.round(a[2] + (b[2] - a[2]) * k),
          Math.round(a[3] + (b[3] - a[3]) * k)
        ];
      }
    }
    return [245, 245, 245];
  }

  var layer = new ol.layer.Image({ opacity: 0.92 });
  var interval = 80;

  function rebuild() {
    layer.setSource(new ol.source.Raster({
      sources: [demSource],
      operation: function (pixels) {
        var src = pixels[0];
        var out = new Uint8ClampedArray(src.length);

        for (var i = 0; i < src.length; i += 4) {
          var elev = src[i] / 255 * MAX_ELEV;

          /* 落在等高线附近的高程画成深色,形成分层线 */
          var frac = elev % interval;
          var nearLine = frac < interval * 0.10 || frac > interval * 0.90;

          if (nearLine) {
            out[i] = 40;
            out[i + 1] = 48;
            out[i + 2] = 42;
          } else {
            var rgb = ramp(elev / MAX_ELEV);
            out[i] = rgb[0];
            out[i + 1] = rgb[1];
            out[i + 2] = rgb[2];
          }
          out[i + 3] = 255;
        }

        return out;
      }
    }));

    document.getElementById('info').textContent =
      '等高距 ' + interval + ' m · 高程上限 ' + MAX_ELEV + ' m';
  }

  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'}), opacity: 0.35 }),
      layer
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.38, 39.92]),
      zoom: 10,
      minZoom: 2
    }),
    controls: ol.control.defaults.defaults({ attribution: false })
  });

  document.getElementById('step').addEventListener('input', function () {
    interval = Number(this.value);
    document.getElementById('stepVal').textContent = interval + ' m';
    rebuild();
  });

  document.getElementById('tgl').addEventListener('change', function () {
    layer.setVisible(this.checked);
  });

  rebuild();
})();
</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 · EXAMPLECoordinate Convert OpenLayers · EXAMPLECustom Circle Render OpenLayers · EXAMPLECustom Control