代码之家  ›  专栏  ›  技术社区  ›  N3tMaster

如何在OpenLayers 3上禁用平滑图像

  •  0
  • N3tMaster  · 技术社区  · 6 年前

    我正在尝试使用OpenLayer查看地图上的图像,我的图像是一个遵循SRID:4326的PNG。我设置了一个OpenLayers地图,并设置了投影信息,以便在OpenLayer SRID(3857)中重新投影我的图像。

    现在我的问题是OpenLayer用平滑的颜色显示分类的PNG。我需要查看没有平滑颜色渲染的PNG。

    实际上,我的OpenLayers地图显示了此图像 enter image description here

    但我需要查看没有平滑颜色的图像。

    enter image description here

    有什么想法吗?

    更新:如果我禁用平滑选项,下面的答案,输出图像将渲染而不平滑。。。但也有一些像素使用错误的颜色渲染(使用较浅的着色器或不透明度较低)

    这是输出图像:

    enter image description here

    但输出应为:

    enter image description here

    3 回复  |  直到 6 年前
        1
  •  2
  •   Viglino Jean-Marc    6 年前

    问题不在于ol,而在于HTML5画布渲染。必须关闭地图画布上的图像平滑。看看 imageSmoothingEnabled option

    使用Openlayers,您可以使用预合成/后合成事件仅对您的层禁用它:

    // Remove image smoothing on precompose
    layer.on('precompose', function(event) {
      var ctx = event.context;
      ctx.mozImageSmoothingEnabled = 
      ctx.webkitImageSmoothingEnabled = 
      ctx.msImageSmoothingEnabled = 
      ctx.imageSmoothingEnabled = false;
    }
    // Restore image smoothing on postcompose
    layer.on('postcompose', function(event) {
      var ctx = event.context;
      ctx.mozImageSmoothingEnabled = 
      ctx.webkitImageSmoothingEnabled = 
      ctx.msImageSmoothingEnabled = 
      ctx.imageSmoothingEnabled = true;
    }
    

    注意:它依赖于导航器。。。

        2
  •  1
  •   Gareth Jones    3 年前

    我知道这是一个老问题,但我已经努力了几个小时,终于成功了,所以我想其他人可能会觉得这很有帮助。

    自OpenLayers 6.4.0 ,可以禁用源的图像平滑(下面的代码示例来自 this example 在OpenLayers网站上):

    var disabledLayer = new TileLayer({
      // specify className so forEachLayerAtPixel can distinguish layers
      className: 'ol-layer-dem',
      source: new XYZ({
        attributions: attributions,
        url:
          'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key,
        maxZoom: 10,
        crossOrigin: '',
        imageSmoothing: false,
      }),
    });
    

    注意:确保设置 imageSmoothing: false 来源 ,而不是图层!如果您在层上设置它,它不会导致任何错误,但它不会实现任何目标;)

    我发现,如果我想让像素化按我预期的方式工作,我需要设置 图像平滑:false 在源上,然后设置 maxZoom 在来源上比我设定的要少 最大缩放 在图层和视图上(例如。 maxZoom: 14 在源上,以及 maxZoom: 19 在图层和视图上)。然后我得到我想要的漂亮的实心块状像素,在任何像素内都没有任何失真或阴影或不正确的值。

    最后,确保 最大缩放 图层上的设置与 最大缩放 设置,否则用户将能够放大太远,图层将消失。

        3
  •  0
  •   N3tMaster    6 年前

    以上答案解决了我的问题。但我也找到了这个解决方案

      map.on('precompose', function(evt) {
        evt.context.imageSmoothingEnabled = false;
        evt.context.webkitImageSmoothingEnabled = false;
        evt.context.mozImageSmoothingEnabled = false;
        evt.context.msImageSmoothingEnabled = false;
    });
    

    有了这段代码,我可以对OL贴图上的每一层禁用平滑。