自定义瓦片处理
TileLayer
的本质就是从服务端请求图片然后绘制,自定义瓦片就在网络请求成功后对瓦片进行更改,然后把新的图片传递给TileLayer
绘制
步骤:
- 拦截瓦片请求
- 处理瓦片
- 新的瓦片传递个
TileLayer
绘制
TIP
例子用到了个颜色插值的库colorin
演示内容
这里我们演示请求地形数据瓦片,然后根据地形的高度自自动配置不同的颜色值,从而形成一个简单的色斑图
拦截瓦片请求
js
const baseLayer = new maptalks.TileLayer("base", {
// debug: true,
urlTemplate: "./../assets/data/tile-rgb/{z}/{x}/{y}.png",
subdomains: ["a", "b", "c", "d"],
});
baseLayer.on("renderercreate", function (e) {
//load tile image
// img(Image): an Image object
// url(String): the url of the tile
e.renderer.loadTileImage = function (img, url) {
//mocking getting image's base64
//replace it by your own, e.g. load from sqlite database
var remoteImage = new Image();
remoteImage.crossOrigin = "anonymous";
remoteImage.onload = function () {
var base64 = getBase64Image(remoteImage);
img.src = base64;
};
remoteImage.onerror = function () {
img.src = get404Image();
};
remoteImage.src = url;
};
});
处理瓦片
js
function getBase64Image(img) {
const { width, height } = img;
tempCanvas = tempCanvas || createCanvas();
tempCanvas.width = width;
tempCanvas.height = height;
var tempCtx = tempCanvas.getContext("2d");
clearCanvas(tempCtx);
tempCtx.drawImage(img, 0, 0);
canvas = canvas || createCanvas();
canvas.width = width;
canvas.height = height;
const imgdata = tempCtx.getImageData(0, 0, width, height);
colorTerrain(imgdata);
var ctx = canvas.getContext("2d");
clearCanvas(ctx);
ctx.putImageData(imgdata, 0, 0);
var dataURL = canvas.toDataURL("image/jpg", 0.7);
return dataURL;
}
解码地形并配色
js
const colors1 = [
[0, "#267300"],
[100, "#428501"],
[150, "#6CA102"],
[200, "#9FC100"],
[250, "#ACCC00"],
[300, "#E0ED04"],
[350, "#FBE100"],
[400, "#FCB600"],
[450, "#FF8D03"],
[500, "#FE2200"],
];
const ci = new colorin.ColorIn(colors1);
function colorTerrain(imgdata) {
const data = imgdata.data;
for (let i = 0, len = data.length; i < len; i += 4) {
const R = data[i],
G = data[i + 1],
B = data[i + 2],
A = data[i + 3];
let height = 0;
//地形解码
height = -10000 + (R * 256 * 256 + G * 256 + B) * 0.1;
height = Math.max(height, 0);
const [r, g, b] = ci.getColor(height);
//根据不同的高度设置不同的颜色
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
}
}
总结
这里只是简单的演示瓦片自定义处理的逻辑,你可以对瓦片做任何的自定义处理,一切取决于你的想象力
包括不限于:
- filter
- clip
- 水印等