<html>
<head>
<title>GrayScale TileLayer Test</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.css" />
<!--[if lte IE 8]>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.js"></script>

<script src="TileLayer.Grayscale.js"></script>
<style>
body { margin: 0; }
#map { height: 100%; }
</style>
<script>
    function init() {
        var map = L.map('map').setView([25.033718,121.56481], 8);
       
	    mapLink = 
							'<a href="http://openstreetmap.org">OpenStreetMap</a>';
						 L.tileLayer.grayscale(
							'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
							attribution: '&copy; ' + mapLink + ' Contributors',
							maxZoom: 18,
							}).addTo(map);
    }
</script>
</head>
<body onload="javascript:init();">
<div id="map"></div>
</body>
</html>
// Code goes here

/* Styles go here */

/*
 * L.TileLayer.Grayscale is a regular tilelayer with grayscale makeover.
 */

L.TileLayer.Grayscale = L.TileLayer.extend({
	options: {
		enableCanvas: true,
		quotaRed: 3,
		quotaGreen: 4,
		quotaBlue: 1,
		quotaDividerTune: 0,
		quotaDivider: function() {
			return this.quotaRed + this.quotaGreen + this.quotaBlue + this.quotaDividerTune;
		}
	},

	initialize: function (url, options) {
		var canvasEl = document.createElement('canvas');
		if( !(canvasEl.getContext && canvasEl.getContext('2d')) ) {
			options.enableCanvas = false;
		}

		L.TileLayer.prototype.initialize.call(this, url, options);
	},

	_loadTile: function (tile, tilePoint) {
		tile.setAttribute('crossorigin', 'anonymous');
		L.TileLayer.prototype._loadTile.call(this, tile, tilePoint);
	},

	_tileOnLoad: function () {
		if (this._layer.options.enableCanvas && !this.canvasContext) {
			var canvas = document.createElement("canvas");
			canvas.width = canvas.height = this._layer.options.tileSize;
			this.canvasContext = canvas.getContext("2d");
		}
		var ctx = this.canvasContext;

		if (ctx) {
			this.onload  = null; // to prevent an infinite loop
			ctx.drawImage(this, 0, 0);
			var imgd = ctx.getImageData(0, 0, this._layer.options.tileSize, this._layer.options.tileSize);
			var pix = imgd.data;
			for (var i = 0, n = pix.length; i < n; i += 4) {
				pix[i] = pix[i + 1] = pix[i + 2] = (this._layer.options.quotaRed * pix[i] + this._layer.options.quotaGreen * pix[i + 1] + this._layer.options.quotaBlue * pix[i + 2]) / this._layer.options.quotaDivider();
			}
			ctx.putImageData(imgd, 0, 0);
			this.removeAttribute("crossorigin");
			this.src = ctx.canvas.toDataURL();
		}

		L.TileLayer.prototype._tileOnLoad.call(this);
	}
});

L.tileLayer.grayscale = function (url, options) {
	return new L.TileLayer.Grayscale(url, options);
};