Skip to content

SVG 图层 ​

SVG 图层示例。 SVG 图层 渲染 transform

借助普通的 ol/Layer 和一个 render 函数,我们可以将交互式 SVG 用作图层。将鼠标悬停在国家上,可以看到完全由 CSS :hover 伪类定义的交互效果。其他图层也可以添加到同一张地图上。蓝色圆点是另一个独立图层上的矢量要素。

main.js
js
import Feature from 'ol/Feature.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Point from 'ol/geom/Point.js';
import Layer from 'ol/layer/Layer.js';
import Vector from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import {composeCssTransform} from 'ol/transform.js';

const map = new Map({
  target: 'map',
  view: new View({
    center: [0, 0],
    extent: [-180, -90, 180, 90],
    projection: 'EPSG:4326',
    zoom: 2,
  }),
});

const svgContainer = document.createElement('div');
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data/world.svg');
xhr.addEventListener('load', function () {
  const svg = xhr.responseXML.documentElement;
  svgContainer.ownerDocument.importNode(svg);
  svgContainer.appendChild(svg);
});
xhr.send();

const width = 2560;
const height = 1280;
const svgResolution = 360 / width;
svgContainer.style.width = width + 'px';
svgContainer.style.height = height + 'px';
svgContainer.style.transformOrigin = 'top left';
svgContainer.className = 'svg-layer';
svgContainer.style.position = 'absolute';

map.addLayer(
  new Layer({
    render: function (frameState) {
      const scale = svgResolution / frameState.viewState.resolution;
      const center = frameState.viewState.center;
      const size = frameState.size;
      const cssTransform = composeCssTransform(
        size[0] / 2,
        size[1] / 2,
        scale,
        scale,
        frameState.viewState.rotation,
        -center[0] / svgResolution - width / 2,
        center[1] / svgResolution - height / 2,
      );
      svgContainer.style.transform = cssTransform;
      svgContainer.style.opacity = String(this.getOpacity());
      return svgContainer;
    },
  }),
);

map.addLayer(
  new Vector({
    source: new VectorSource({
      features: [new Feature(new Point([0, 0]))],
    }),
    style: {
      'circle-fill-color': 'blue',
      'circle-radius': 10,
      'circle-stroke-color': 'white',
    },
  }),
);
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>SVG 图层</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      #map {
        background: black;
      }

      .svg-layer path:hover {
        opacity: 0.4;
      }

      .ol-layer {
        pointer-events: none;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "svg-layer",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}