图层 Swipe (WebGL)
图层 Swipe (WebGL)示例。 滑动 WebGL
WebGL 瓦片图层上的 prerender 和 postrender 事件可用于在渲染前后操作 WebGL 上下文。在本示例中,调用了 gl.scissor() 方法,根据滑块的位置对上层图层进行裁剪。 注意:本示例非常简化,之所以能正常工作是因为只渲染了一个 WebGL 图层。如果各图层绘制到不同的上下文,可能同样可行。但对于绘制到同一个上下文的多个图层——例如将多个图层的 'className' 属性都设置为 'canvas3d'——该方式并不适用。在这种情况下,明智的做法是使用 'gl.clear' 以及对 prerender/postrender 事件的其他调整来修改你的代码。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import {getRenderPixel} from 'ol/render.js';
import ImageTile from 'ol/source/ImageTile.js';
import OSM from 'ol/source/OSM.js';
const osm = new TileLayer({
source: new OSM({wrapX: true}),
});
const key = 'Get your own API key at https://www.maptiler.com/cloud/';
const imagery = new TileLayer({
source: new ImageTile({
url: 'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}.jpg?key=' + key,
attributions:
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>',
maxZoom: 20,
}),
});
const map = new Map({
layers: [osm, imagery],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const swipe = document.getElementById('swipe');
imagery.on('prerender', function (event) {
const gl = event.context;
gl.enable(gl.SCISSOR_TEST);
const mapSize = map.getSize(); // 以 CSS 像素为单位的 [宽度, 高度]
// 根据给定的 CSS 坐标获取渲染坐标和尺寸
const bottomLeft = getRenderPixel(event, [0, mapSize[1]]);
const topRight = getRenderPixel(event, [mapSize[0], 0]);
const width = Math.round(
(topRight[0] - bottomLeft[0]) * (Number(swipe.value) / 100),
);
const height = topRight[1] - bottomLeft[1];
gl.scissor(bottomLeft[0], bottomLeft[1], width, height);
});
imagery.on('postrender', function (event) {
const gl = event.context;
gl.disable(gl.SCISSOR_TEST);
});
swipe.addEventListener('input', function () {
map.render();
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图层滑动 (WebGL)</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<input id="swipe" type="range" style="width: 100%">
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "webgl-layer-swipe",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}