Atlaslog
Atlaslog / Examples / OpenLayers / Layer Clipping Vector
OpenLayers · Runnable Example

Layer Clipping Vector

Runnable OpenLayers example: Layer Clipping Vector. 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-layer-clipping-vector.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-layer-clipping-vector.html
<!--
  示例:矢量图层裁剪
  要点:在图层 prerender 时按多边形像素路径 clip,postrender 时恢复上下文
  依赖: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:14px;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="checkbox" id="clip" checked> 启用裁剪</label>
  <span>裁剪范围由要素多边形决定,随地图缩放实时重算像素路径</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 fromLonLat = ol.proj.fromLonLat;

  /* 裁剪范围:一个不规则多边形 */
  var clipRing = [
    [116.33, 39.955], [116.44, 39.975], [116.50, 39.918],
    [116.455, 39.862], [116.352, 39.876], [116.315, 39.918], [116.33, 39.955]
  ].map(function (c) { return fromLonLat(c); });

  /* 被裁剪的内容:一大片网格状的点与线 */
  var vecSource = new ol.source.Vector();

  for (var i = 0; i <= 20; i++) {
    for (var j = 0; j <= 14; j++) {
      var lon = 116.28 + i * 0.0118;
      var lat = 39.83 + j * 0.0106;
      var f = new ol.Feature({ geometry: new ol.geom.Point(fromLonLat([lon, lat])) });
      f.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 4,
          fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.85)' })
        })
      }));
      vecSource.addFeature(f);
    }
  }

  [39.86, 39.90, 39.94].forEach(function (lat) {
    var f = new ol.Feature({
      geometry: new ol.geom.LineString([fromLonLat([116.28, lat]), fromLonLat([116.55, lat])])
    });
    f.setStyle(new ol.style.Style({
      stroke: new ol.style.Stroke({ color: 'rgba(180,35,24,0.75)', width: 3 })
    }));
    vecSource.addFeature(f);
  });

  var dataLayer = new ol.layer.Vector({ source: vecSource });

  var outline = new ol.Feature({ geometry: new ol.geom.Polygon([clipRing]) });
  outline.setStyle(new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(250,193,86,0.10)' }),
    stroke: new ol.style.Stroke({ color: '#a9700f', width: 2, lineDash: [8, 5] })
  }));

  var outlineLayer = new ol.layer.Vector({
    source: new ol.source.Vector({ features: [outline] }),
    zIndex: 20
  });

  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'}) }), dataLayer, outlineLayer],
    view: new ol.View({ center: fromLonLat([116.41, 39.92]), zoom: 12 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  var clipEnabled = true;

  dataLayer.on('prerender', function (event) {
    if (!clipEnabled) return;

    var ctx = event.context;
    ctx.save();
    ctx.beginPath();

    clipRing.forEach(function (coord, idx) {
      var px = map.getPixelFromCoordinate(coord);
      if (idx === 0) ctx.moveTo(px[0], px[1]);
      else ctx.lineTo(px[0], px[1]);
    });

    ctx.closePath();
    ctx.clip();
  });

  dataLayer.on('postrender', function (event) {
    if (!clipEnabled) return;
    event.context.restore();
  });

  document.getElementById('clip').addEventListener('change', function () {
    clipEnabled = this.checked;
    dataLayer.changed();
  });
})();
</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 · EXAMPLELayer Extent OpenLayers · EXAMPLELayer Group OpenLayers · EXAMPLELayer Opacity