teknocreator teknocreator - 1 year ago 151
Javascript Question

Turn off image smoothing in OpenLayers 3

I realize this is probably a duplicate question of this one: Rendering images pixelated with OpenLayers 3.

However, there hasn't been a response or comments. So, thought I'd ask it as well while providing a bit code.

I'm modifying/updating a web page that displays PNG images of various weather-related elements (e.g. temperature) to use OpenLayers 3 instead of 2 as OpenLayers will allow us to use its additional features. My customer needs the actual pixels displayed upon zooming in versus smoothed. In OpenLayers 2, I just needed to add the image-rendering CSS, i.e.

.olTileImage {
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast;/* Webkit (non-standard naming) */
image-rendering: crisp-edges;
-ms-interpolation-mode: nearest-neighbor; /* IE (non-standard property) */

However, if I attempt to do the same thing on the .ol-viewport, .ol-unselectable, img, and canvas classes/elements, nothing happens and the image is still smoothed when zooming in.

This is how I'm declaring the layer:

fcstoverlay = new ol.layer.Image({
type: 'overlay',
opacity: 0.5,
title: 'Forecast',
name: 'imgforecast',

source: new ol.source.ImageStatic({
url: "images/ndfd/conus/mercator/maxt_2016020200.png",
imageSize: [3328, 2048],
imageExtent: [-15028131.257, 1878516.407,-6887893.493, 6887893.493],
projection: ovProj

visible: true


The layer loads just fine, but zooming in displays a smoothed/anti-aliased image which I need to be turned off.

Answer Source

OpenLayers 3 uses a canvas renderer by default. With that renderer, it is easy to achieve what you want, by setting the imageSmoothingEnabled property of the canvas context to false before the map image is composed. The snippet below assumes that your map variable holds your ol.Map instance.

map.on('precompose', function(evt) {
  evt.context.imageSmoothingEnabled = false;
  evt.context.webkitImageSmoothingEnabled = false;
  evt.context.mozImageSmoothingEnabled = false;
  evt.context.msImageSmoothingEnabled = false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download