Atlaslog
Atlaslog / Examples / OpenLayers / WMS Image Svg
OpenLayers · Runnable Example

WMS Image Svg

Runnable OpenLayers example: WMS Image Svg. 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-wms-image-svg.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-wms-image-svg.html
<!--
  示例:OpenLayers SVG 格式 WMS
  要点:Image 源的自定义 loader 返回 SVG 图片,矢量图形随缩放保持清晰
  依赖: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>SVG 格式 WMS</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:10px;align-items:center;flex-wrap:wrap;font-size:12px;color:#58606e}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  .bar select,.bar input[type=range]{font-size:12px}
  .bar .val{font-family:ui-monospace,Consolas,monospace;color:#1f5fd0;min-width:44px}
  .bar .sep{width:1px;height:16px;background:#d8dce2}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <span>FORMAT image/svg+xml</span>
  <span class="sep"></span>
  <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').textContent = 'OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net';
    return;
  }

  /* ---- 页面内合成的区县面,代替外部 WMS 服务返回的影像 ---- */
  var SYNTH_REGIONS = [
    {name: '海淀', color: '#a9c9ec', pts: [[116.14, 39.94], [116.34, 39.94], [116.34, 40.06], [116.14, 40.06]]},
    {name: '朝阳', color: '#b7dbb2', pts: [[116.44, 39.90], [116.62, 39.90], [116.62, 40.05], [116.44, 40.05]]},
    {name: '西城', color: '#efcf9f', pts: [[116.32, 39.88], [116.40, 39.88], [116.40, 39.96], [116.32, 39.96]]},
    {name: '东城', color: '#e8aabf', pts: [[116.40, 39.88], [116.48, 39.88], [116.48, 39.96], [116.40, 39.96]]},
    {name: '丰台', color: '#bdafd9', pts: [[116.18, 39.78], [116.40, 39.78], [116.40, 39.88], [116.18, 39.88]]},
    {name: '大兴', color: '#9ed0c9', pts: [[116.28, 39.62], [116.56, 39.62], [116.56, 39.78], [116.28, 39.78]]}
  ];

  var SYNTH_RIVER = [[116.10, 40.00], [116.22, 39.95], [116.34, 39.94], [116.45, 39.90], [116.58, 39.86]];

  function synthParam(src, name) {
    var m = new RegExp('[?&]' + name + '=([^&]*)').exec(src || '');
    return m ? decodeURIComponent(m[1].replace(/\+/g, ' ')) : '';
  }

  function synthDraw(ctx, w, h, bbox, opt) {
    opt = opt || {};
    var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
    if (!isFinite(x0) || !(x1 > x0) || !(y1 > y0)) {
      return;
    }
    var project = opt.project || ol.proj.fromLonLat;
    function px(c) {
      return [(c[0] - x0) / (x1 - x0) * w, (y1 - c[1]) / (y1 - y0) * h];
    }
    ctx.fillStyle = opt.background || '#eef2f6';
    ctx.fillRect(0, 0, w, h);

    /* 河流 */
    var river = SYNTH_RIVER.map(function (p) { return px(project(p)); });
    ctx.beginPath();
    ctx.moveTo(river[0][0], river[0][1]);
    for (var r = 1; r < river.length; ++r) {
      ctx.lineTo(river[r][0], river[r][1]);
    }
    ctx.strokeStyle = '#7fb6d9';
    ctx.lineWidth = Math.max(2, w / 60);
    ctx.stroke();

    /* 区县面 */
    var palette = opt.palette;
    SYNTH_REGIONS.forEach(function (region, i) {
      var pts = region.pts.map(function (p) { return px(project(p)); });
      ctx.beginPath();
      ctx.moveTo(pts[0][0], pts[0][1]);
      for (var j = 1; j < pts.length; ++j) {
        ctx.lineTo(pts[j][0], pts[j][1]);
      }
      ctx.closePath();
      ctx.globalAlpha = 0.88;
      ctx.fillStyle = palette ? palette[i % palette.length] : region.color;
      ctx.fill();
      ctx.globalAlpha = 1;
      ctx.strokeStyle = '#5c6b7a';
      ctx.lineWidth = 1;
      ctx.stroke();

      if (w >= 200) {
        var cx = 0, cy = 0;
        pts.forEach(function (p) { cx += p[0]; cy += p[1]; });
        cx /= pts.length;
        cy /= pts.length;
        ctx.fillStyle = '#24313d';
        ctx.font = '500 ' + Math.max(9, Math.round(w / 22)) + 'px sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(region.name, cx, cy);
      }
    });

    /* 时间动画用的降水色块 */
    if (opt.time) {
      var seed = 0;
      for (var k = 0; k < opt.time.length; ++k) {
        seed = (seed * 31 + opt.time.charCodeAt(k)) % 9973;
      }
      ctx.globalAlpha = 0.35;
      for (var n = 0; n < 5; ++n) {
        var fx = ((seed + n * 137) % 100) / 100;
        var fy = ((seed + n * 71) % 100) / 100;
        ctx.beginPath();
        ctx.ellipse(fx * w, fy * h, w / 12, h / 18, 0, 0, Math.PI * 2);
        ctx.fillStyle = n % 2 ? '#7cc4f2' : '#3f8fd2';
        ctx.fill();
      }
      ctx.globalAlpha = 1;
    }

    /* 维度参数演示用的淹没面 */
    if (typeof opt.threshold === 'number') {
      var levelY = y1 - (y1 - y0) * (0.15 + opt.threshold / 400);
      var flood = [[x0, y0], [x1, y0], [x1, levelY], [x0, levelY]].map(px);
      ctx.beginPath();
      ctx.moveTo(flood[0][0], flood[0][1]);
      for (var q = 1; q < flood.length; ++q) {
        ctx.lineTo(flood[q][0], flood[q][1]);
      }
      ctx.closePath();
      ctx.globalAlpha = 0.45;
      ctx.fillStyle = '#2f74c0';
      ctx.fill();
      ctx.globalAlpha = 1;
    }

    ctx.strokeStyle = 'rgba(90, 105, 120, 0.25)';
    ctx.lineWidth = 1;
    ctx.strokeRect(0.5, 0.5, w - 1, h - 1);
  }

  function synthToURL(w, h, bbox, opt) {
    var canvas = document.createElement('canvas');
    canvas.width = Math.max(1, Math.round(w));
    canvas.height = Math.max(1, Math.round(h));
    synthDraw(canvas.getContext('2d'), canvas.width, canvas.height, bbox, opt);
    return canvas.toDataURL('image/png');
  }

  function synthWmsTile(tile, src, opt) {
    var bbox = synthParam(src, 'BBOX').split(',').map(Number);
    var w = parseInt(synthParam(src, 'WIDTH'), 10) || 256;
    var h = parseInt(synthParam(src, 'HEIGHT'), 10) || 256;
    if (bbox.length === 4) {
      tile.getImage().src = synthToURL(w, h, bbox, opt);
    }
  }

  function synthWmsImage(image, src, opt) {
    var bbox = synthParam(src, 'BBOX').split(',').map(Number);
    var w = parseInt(synthParam(src, 'WIDTH'), 10) || 512;
    var h = parseInt(synthParam(src, 'HEIGHT'), 10) || 512;
    if (bbox.length === 4) {
      image.getImage().src = synthToURL(w, h, bbox, opt);
    }
  }

  function synthExtent(source, tile) {
    var coord = tile.getTileCoord();
    return coord && source.getTileGrid() ? source.getTileGrid().getTileCoordExtent(coord) : null;
  }


  var extent = ol.proj.transformExtent(
    [115.9, 39.6, 116.7, 40.1],
    'EPSG:4326',
    'EPSG:3857'
  );

  function buildSvg() {
    var width = 800;
    var height = 500;
    var x0 = extent[0];
    var y0 = extent[1];
    var x1 = extent[2];
    var y1 = extent[3];

    function toPixel(lonlat) {
      var coordinate = ol.proj.fromLonLat(lonlat);
      return [
        (coordinate[0] - x0) / (x1 - x0) * width,
        (y1 - coordinate[1]) / (y1 - y0) * height
      ];
    }

    var parts = [
      '<svg xmlns="http://www.w3.org/2000/svg" width="' + width +
        '" height="' + height + '" viewBox="0 0 ' + width + ' ' + height + '">',
      '<rect width="100%" height="100%" fill="#eef2f6"/>'
    ];

    SYNTH_REGIONS.forEach(function (region) {
      var points = region.pts.map(toPixel).map(function (p) {
        return p[0].toFixed(1) + ',' + p[1].toFixed(1);
      }).join(' ');
      parts.push('<polygon points="' + points + '" fill="' + region.color +
        '" fill-opacity="0.85" stroke="#5c6b7a" stroke-width="1"/>');
      var center = region.pts.map(toPixel).reduce(function (acc, p) {
        return [acc[0] + p[0] / region.pts.length, acc[1] + p[1] / region.pts.length];
      }, [0, 0]);
      parts.push('<text x="' + center[0] + '" y="' + center[1] +
        '" font-family="sans-serif" font-size="16" text-anchor="middle" ' +
        'fill="#24313d">' + region.name + '</text>');
    });

    parts.push('</svg>');
    return parts.join('');
  }

  var svgUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(buildSvg());

  var imageSource = new ol.source.Image({
    loader: function () {
      return new Promise(function (resolve, reject) {
        var image = new Image();
        image.onload = function () {
          resolve(image);
        };
        image.onerror = function () {
          reject(new Error('SVG 影像加载失败'));
        };
        image.src = svgUrl;
      });
    }
  });

  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.5}),
      new ol.layer.Image({source: imageSource, extent: extent})
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.35, 39.90]),
      zoom: 9
    })
  });

  document.getElementById('info').textContent =
    '范围 ' + extent.map(function (value) {
      return Math.round(value);
    }).join(', ');

})();
</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 · EXAMPLEWMS No Proj OpenLayers · EXAMPLEWMS Params OpenLayers · EXAMPLEWMS Tiled