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

时间:2018-04-04 16:29:05

标签: javascript gis openlayers

我正在尝试使用OpenLayer在地图上查看图像,我的图像是遵循SRID的PNG:4326。我设置了一个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 个答案:

答案 0 :(得分:2)

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

使用Openlayers,您可以使用precompose / postcompose事件仅为您的图层禁用它:

// 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;
}

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

答案 1 :(得分:1)

我现在知道这是一个老问题,但我已经为此纠结了几个小时,终于让它起作用了,所以我认为其他人可能会觉得这有帮助。

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

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,而不是在图层上!如果你在图层上设置它不会导致任何错误,但它不会实现任何东西;)

我发现如果我希望像素化以我期望的方式工作,我需要在源上设置 imageSmoothing: false,然后在源上设置 maxZoom 小于什么我在图层和视图上设置为 maxZoom(例如在源上设置为 maxZoom: 14,在图层和视图上设置为 maxZoom: 19)。然后我得到了我想要的漂亮的实心块状像素,任何像素内都没有任何失真、阴影或不正确的值。

最后,请确保您图层上的 maxZoom 设置与视图中的 maxZoom 设置相同,否则您的用户将无法放大太多而您的图层将消失。

答案 2 :(得分:0)

上面的答案解决了我的问题。但我也发现了这个解决方案

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

使用此代码,我可以为OL地图上的每个图层禁用平滑。