* @function Util.setMask * @description 为图层设置掩膜。 * @version 10.1.0 * @param {ol.layer.Layer|Array. } layers 图层 * @param {ol.geom.Geometry|ol.Feature} polygon 掩膜矢量要素,支持面类型的要素。
(layers, polygon)
| 406 | * @param {ol.geom.Geometry|ol.Feature} polygon 掩膜矢量要素,支持面类型的要素。 |
| 407 | */ |
| 408 | setMask(layers, polygon) { |
| 409 | if (!polygon) { |
| 410 | return; |
| 411 | } |
| 412 | const geo = polygon instanceof Feature ? polygon.getGeometry() : polygon; |
| 413 | if (!(geo instanceof Geometry) && ['MultiPolygon', 'Polygon'].indexOf(polygon.getType()) < 0) { |
| 414 | return; |
| 415 | } |
| 416 | const feature = polygon instanceof Feature ? polygon : new Feature(polygon); |
| 417 | const style = new Style({ |
| 418 | fill: new Fill({ |
| 419 | color: 'black' |
| 420 | }) |
| 421 | }); |
| 422 | |
| 423 | const clipLayer = new VectorLayer({ |
| 424 | source: new VectorSource({ |
| 425 | features: [feature], |
| 426 | wrapX: false |
| 427 | }) |
| 428 | }); |
| 429 | |
| 430 | const clipRender = function (e) { |
| 431 | const vectorContext = getVectorContext(e); |
| 432 | e.context.globalCompositeOperation = 'destination-in'; |
| 433 | clipLayer.getSource().forEachFeature(function (feature) { |
| 434 | vectorContext.drawFeature(feature, style); |
| 435 | e.context.globalCompositeOperation = 'source-over'; |
| 436 | }); |
| 437 | }; |
| 438 | const todoLayers = Array.isArray(layers) ? layers : [layers]; |
| 439 | unsetMask(todoLayers); |
| 440 | todoLayers.forEach((layer) => { |
| 441 | layer.classNameBak_ = layer.className_; |
| 442 | layer.className_ = `ol_mask_layer_${layer.ol_uid}`; |
| 443 | layer.clipRender = clipRender; |
| 444 | layer.extentBak_ = layer.getExtent(); |
| 445 | layer.setExtent(clipLayer.getSource().getExtent()); |
| 446 | layer.on('postrender', clipRender); |
| 447 | layer.changed(); |
| 448 | }); |
| 449 | }, |
| 450 | /** |
| 451 | * @function Util.unsetMask |
| 452 | * @description 取消图层掩膜。 |