首页 > 解决方案 > mapbox gl js:使用中间渲染步骤作为自定义图层的掩码

问题描述

我的目标是制作一个带有自定义图层的 mapbox 地图。该自定义图层应被其他 mapbox 地图掩盖。

用例:

我有一些默认地图。最重要的是,我想渲染一些特殊的热图。该热图只能显示在道路上方。

目前的做法:

问题:

图层的渲染顺序似乎与它们添加到 mapbox 的顺序不匹配。这个例子有一个自定义层,它在调用它时输出帧缓冲区中中心像素的颜色:

var map = window.map = new mapboxgl.Map({
container: 'map',
zoom: 16,
center: [8.30468, 47.05232],
style: {
    "version":8, 
    "name":"test", 
    "sources": {
        "openmaptiles": {
            "type": "vector",
            "url": "https://api.maptiler.com/tiles/v3/tiles.json?key=X0HhMcrAjHfR6MvFLSSn"
        }
    },
    "layers":[]}
});

var getPixelLayer = {
    id: 'highlight',
    type: 'custom',

    onAdd: function (map, gl) { },

    render: function (gl, matrix) {
        var pixels = new Uint8Array(4);
        gl.readPixels(Math.round(gl.drawingBufferWidth/2), Math.round(gl.drawingBufferHeight/2), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
        document.getElementById("color").innerHTML = pixels[0]+","+pixels[1]+","+pixels[2];
    }
};

map.on('load', function() {
  //expected output: "255,255,255" everywhere
  //actual output: "0,0,0" everywhere
    /*
    map.addLayer({"id":"bkg1","paint":{"background-color":"rgb(255, 255, 255)"},"type":"background"});
    map.addLayer(getPixelLayer);
    map.addLayer({"id":"bkg2","paint":{"background-color":"rgb(0, 0, 0)"},"type":"background"});
    */

  //expected output: "0,0,0" everywhere
  //actual output: "177,177,177" above buildings
  //               "0,0,0" above streets
  //               "0,0,0" above background
    map.addLayer({"id":"bkg1","paint":{"background-color":"rgb(0, 0, 0)"},"type":"background"});
    map.addLayer(getPixelLayer);
    map.addLayer({"id":"roads","layout":{"line-cap":"round","line-join":"round","visibility":"visible"},"paint":{"line-color":"#fff","line-offset":0,"line-width":{"base":1.4,"stops":[[8,1.2],[16,12]]}},"source":"openmaptiles","source-layer":"transportation","type":"line"});
    map.addLayer({"id":"building","paint":{"fill-color":"rgb(177, 177, 177)"},"source":"openmaptiles","source-layer":"building","type":"fill"});


});

https://jsfiddle.net/t31cj5v0/

可以看出,渲染顺序似乎是 background->buildings->custom_layer->streets 而不是 background->custom_layer->streets->buildings。最后,图层顺序在屏幕上显示是正确的,但是像这样做我想做的事是不可能的。

有谁知道导致这种行为的原因以及如何避免这种行为?

我尝试过的其他实现:

我还尝试将黑白街道地图渲染为具有同步运动的不同地图框对象。这可行,但由于每个地图框都有自己的 webgl 上下文,我不能在其他上下文中使用生成的黑白纹理。

功能要求 (?)

如果可以实现一些“掩码”层来实现这个目标,那就太好了。但现在我只是在寻找一些技巧来做到这一点。提前致谢。

标签: javascriptmapboxmapbox-gl-jsmapbox-gl

解决方案


mapbox 层在 3 个渲染通道中绘制。“离屏”、“不透明”和“半透明”。“屏幕外”并不重要,因为随后的通道总是在它上面绘制。问题出现是因为首先绘制了所有分类为“不透明”的图层,然后绘制了所有分类为“半透明”的图层(在渲染过程中,图层顺序受到尊重)。因此,渲染顺序与声明的顺序不匹配。

自定义图层在“半透明”通道中绘制,但由于上述原因,可能会发生后面的图层已经渲染(如果“不透明”)。通常这不是问题,因为 mapbox 使用模板缓冲区来跟踪哪个图层在哪个图层之下/哪个图层之上,即使它们没有按顺序绘制。

要使渲染顺序匹配,请在创建 mapbox 实例后添加此行。它将禁用“不透明”渲染通道并强制“不透明”的每个图层都“半透明”:

map.painter.opaquePassEnabledForLayer = function() { return false; }

推荐阅读