利用oplayers任意更换WMTS瓦片颜色
利用oplayers任意更换WMTS瓦片颜色
从官方代码得到启示,然后咱们举一反三去实现
官方案例
openlayers3开始,其底层渲染从SVG切换到了canvas,据说渲染效率提高了不少
openlayers官方给出了标准案例:
链接: https://openlayers.org/en/latest/examples/color-manipulation.html自己看;
原理就是:
map.on('precompose', function(evt){
var ctx = evt.context;
ctx.filter = filter;//设置滤镜值
})
map.render();
filter值类型为字符串,默认值为"none";
precompose事件会在地图渲染前发生,因此在渲染前,改变filter值,即可让地图按设置的滤镜进行渲染。
直接上代码自己干
先看原图
设置成灰色
1)灰度滤镜: 设置filter值为 grayscale(100%)
2)褐色: 设置filter值为 sepia(100%)
3)复合滤镜
可以使用多个滤镜,值之间用空格隔开,如:contrast(150%) saturate(200%)
js代码片
.
var app = {
baseLayer: undefined,
map: undefined,
filter: 'none',
key: undefined,
init: function(){
this.baseLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
})
});
this.map = new ol.Map({
target: 'map',
view: new ol.View({
projection: 'EPSG:4326',
center: [118, 36],
zoom: 7
}),
layers: [this.baseLayer]
});
this.map.on('precompose', function(evt){
let ctx = evt.context;
ctx.filter = this.filter;
}.bind(this))
}
}
app.init();
function fs(type){
switch (type) {
//反色
case 'invert':
type = 'invert' + '(100%)'
break;
//褐色
case 'sepia':
type = 'sepia' + '(100%)'
break;
//灰度
case 'grayscale':
type = 'grayscale' + '(100%)'
break;
//复合
case 'complex':
type = 'contrast(150%) saturate(200%)'
break;
//默认
default:
type = 'none';
break;
}
app.filter = type;
app.map.render();
}
html代码片
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<title>滤镜</title>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
<style>
head,body, #map{
height: 100%;
width: 100%;
margin: 0%;
padding: 0%;
}
.ol-attribution{
display: none;
}
.ol-zoom{
display: none;
}
.input-group-btn{
top: 2%;
left: 1%;
z-index: 1;
position: absolute;
}
</style>
</head>
<body>
<div id="app">
<div id="map"></div>
<div class="input-group-btn">
<button type="button" class="btn btn-default" onclick="fs('invert')">反色</button>
<button type="button" class="btn btn-default" onclick="fs('sepia')">褐色</button>
<button type="button" class="btn btn-default" onclick="fs('grayscale')">灰度</button>
<button type="button" class="btn btn-default" onclick="fs('complex')">复合滤镜</button>
<button type="button" class="btn btn-default" onclick="fs('none')">原色</button>
</div>
</div>
<script src="./app.js"></script>
</body>
</html>