本篇介绍一下使用openlayers 自定义瓦片(切片)颜色
1 需求
- 自定义瓦片(切片)颜色
2 分析
使用各种source的tileLoadFunction属性
4 实现
修改前:
修改后:
<template>
<div id="map" class="map"></div>
</template>
<script setup lang="ts">
import { Map, View } from 'ol';
import { Tile as TileLayer } from 'ol/layer';
import { get } from 'ol/proj';
import { XYZ } from 'ol/source';
const projection = get('EPSG:4326');
const layerTypeMap = {
vector: ['vec', 'cva'], // [矢量底图, 矢量注记]
image: ['img', 'cia'], // [影像底图, 影像注记]
terrain: ['ter', 'cta'] // [地形晕渲, 地形注记]
};
const map = ref();
onMounted(() => {
initMap('image');
});
const initMap = (layerType = 'image') => {
const key = '替换为天地图key';
// c: 经纬度投影 w: 墨卡托投影
const matrixSet = 'c';
map.value = new Map({
target: 'map',
layers: [
// 底图
new TileLayer({
source: new XYZ({
url: `https://t{0-7}.tianditu.gov.cn/DataServer?T=${layerTypeMap[layerType][0]}_${matrixSet}&tk=${key}&x={x}&y={y}&l={z}`,
projection,
tileLoadFunction:handleTileLoadFunction
})
}),
// 注记
new TileLayer({
source: new XYZ({
url: `https://t{0-7}.tianditu.gov.cn/DataServer?T=${layerTypeMap[layerType][1]}_${matrixSet}&tk=${key}&x={x}&y={y}&l={z}`,
projection,
})
})
],
view: new View({
center: [116.406393, 39.909006],
projection: projection,
zoom: 5,
maxZoom: 17,
minZoom: 1
})
});
};
const handleTileLoadFunction=(imageTile: any, src: string) => {
// 该函数默认为imageTile.getImage().src = src;
// 以下为自定义
let img = new Image();
img.setAttribute('crossOrigin', 'Anonymous');
img.src = src;
img.onload = () => {
let canvas = document.createElement('canvas');
let w = img.width;
let h = img.height;
canvas.width = w;
canvas.height = h;
let context = canvas.getContext('2d');
context!.filter = 'hue-rotate(100deg)';
context?.drawImage(img, 0, 0, w, h, 0, 0, w, h);
const imageData = context!.getImageData(0, 0, canvas.width, canvas.height);
const pixelData = imageData?.data ?? [];
// pixelData 为数组 是[r,g,b,a]的循环结构
for (let i = 0; i < pixelData.length; i++) {
// pixelData[i * 4 + 0] r 通道;
// pixelData[i * 4 + 1] g 通道;
// pixelData[i * 4 + 2] b 通道;
// pixelData[i * 4 + 3] a 通道;
}
context!.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
imageTile.getImage().src = canvas.toDataURL('image/png');
};
};
</script>
<style scoped lang="scss">
.map {
width: 100%;
height: 100%;
}
</style>