openlayers 自定义瓦片(切片)颜色

本篇介绍一下使用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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值