本篇介绍一下使用vue3-openlayers 自定义瓦片(切片)颜色
1 需求
- 自定义瓦片(切片)颜色
2 分析
使用各种source的tileLoadFunction属性
3 实现
修改前:
修改后:
<template>
<ol-map
:loadTilesWhileAnimating="true"
:loadTilesWhileInteracting="true"
style="width: 100%; height: 100%"
ref="mapRef"
>
<ol-view
ref="view"
:center="center"
:rotation="rotation"
:zoom="zoom"
:projection="projection"
/>
<ol-tile-layer>
<ol-source-xyz
:projection="projection"
:url="imageUrl"
:tileLoadFunction="handleTileLoadFunction"
/>
</ol-tile-layer>
<ol-tile-layer :opacity="0.9">
<ol-source-xyz :projection="projection" :url="addressUrl" />
</ol-tile-layer>
</ol-map>
</template>
<script setup lang="ts">
const center = ref([121, 31]);
const projection = ref('EPSG:4326');
const zoom = ref(5);
const rotation = ref(0);
const mapRef = ref();
const layerImage = ref('img');
const layerAddress = ref('cia');
const matrixSet = ref('c'); //c: 经纬度投影 w: 墨卡托投影
// 影像底图
const imageUrl = ref(
`https://t{0-7}.tianditu.gov.cn/DataServer?T=${layerImage.value}_${matrixSet.value}&tk=${key}&x={x}&y={y}&l={z}`
);
// 影像注记
const addressUrl = ref(
`https://t{0-7}.tianditu.gov.cn/DataServer?T=${layerAddress.value}_${matrixSet.value}&tk=${key}&x={x}&y={y}&l={z}`
);
const key = '替换为天地图key';
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"></style>