OL3 OSM canvas to greyscale

by LandsD Map API

HTML

<script src="http://openlayers.org/en/v3.0.0/build/ol.js"></script>
<body onload="Initialize();">
  <p><b>Canvas With OpenLayers &amp; HTML5 Canvas Demo</b>
  </p>
  <div>
    <div id="map" class="map" style="width:400px;height:400px;border:1px solid black;"></div>
  </div>
</body>

CSS

body {
	  font-family: sans-serif;
	}
	
	p {
	  width: 95%;
	}
	
	a {
	  text-decoration: none;
	  color: black;
	  font-weight: bold;
	  font-size: 1.1em;
	}
	
	div.map {
	  width: 45%;
	  height: 90%;
	  float: left;
	  border-style: solid;
	  border-right-width: 5%;
	}

JavaScript

//***************************************
		// Initialize Map
		//***************************************
		function Initialize() {

		  var imagery = new ol.layer.Tile({
		    source: new ol.source.OSM()
		  });


		  var map = new ol.Map({
		    target: 'map',
		    layers: [imagery],
		    view: new ol.View({
		      center: ol.proj.transform([-2.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
		      zoom: 6
		    })
		  });


		  //Apply a filter on "postcompose" events.
		  imagery.on('postcompose', function(event) {
		    greyscale(event.context);
		  });

		}

		//***************************************
		// Aux Func.
		//***************************************

		// function applies greyscale to every pixel in canvas
		function greyscale(context) {
		  var width = context.canvas.width;
		  var height = context.canvas.height;
		  console.log('width: ' + width);
		  console.log('height: ' + height);

		  var inputData = context.getImageData(0, 0, width, height).data;
		  console.log('inputData.length: ' + inputData.length);

		  var canvas = document.getElementsByClassName('ol-unselectable')[0];
		  var ctx = canvas.getContext('2d');
		  ctx.fillStyle = "rgba(0, 0, 0, 0)"
		  var myImageData = ctx.createImageData(width, height);
		  var d = myImageData.data;

		  for (i = 0; i < inputData.length; i += 4) {

		    var r = inputData[i];
		    var g = inputData[i + 1];
		    var b = inputData[i + 2];
		    // CIE luminance for the RGB
		    var v = 0.2126 * r + 0.7152 * g + 0.0722 * b;
		    d[i + 0] = v; // Red
		    d[i + 1] = v; // Green
		    d[i + 2] = v; // Blue
		    d[i + 3] = 255; // Alpha

		  }
		  ctx.putImageData(myImageData, 0, 0);

		}