├── README.md └── TileLayer.Grayscale.js /README.md: -------------------------------------------------------------------------------- 1 | # Leaflet.TileLayer.Grayscale 2 | 3 | A regular TileLayer with grayscale makeover. 4 | 5 | ## Usage 6 | 7 | Just use `L.tileLayer.grayscale(url, options)` instead of `L.tileLayer(url, options)`. 8 | 9 | I recommend using `fadeAnimation: false` option when creating the map object. Otherwise you 10 | will see a lot of flickering. 11 | 12 | ## Example 13 | 14 | https://zverik.github.io/leaflet-grayscale/ 15 | 16 | ## License 17 | 18 | This plugin was written by Ilya Zverev and published under WTFPL license. 19 | -------------------------------------------------------------------------------- /TileLayer.Grayscale.js: -------------------------------------------------------------------------------- 1 | /* 2 | * L.TileLayer.Grayscale is a regular tilelayer with grayscale makeover. 3 | */ 4 | 5 | L.TileLayer.Grayscale = L.TileLayer.extend({ 6 | options: { 7 | quotaRed: 21, 8 | quotaGreen: 71, 9 | quotaBlue: 8, 10 | quotaDividerTune: 0, 11 | quotaDivider: function() { 12 | return this.quotaRed + this.quotaGreen + this.quotaBlue + this.quotaDividerTune; 13 | } 14 | }, 15 | 16 | initialize: function (url, options) { 17 | options = options || {} 18 | options.crossOrigin = true; 19 | L.TileLayer.prototype.initialize.call(this, url, options); 20 | 21 | this.on('tileload', function(e) { 22 | this._makeGrayscale(e.tile); 23 | }); 24 | }, 25 | 26 | _createTile: function () { 27 | var tile = L.TileLayer.prototype._createTile.call(this); 28 | tile.crossOrigin = "Anonymous"; 29 | return tile; 30 | }, 31 | 32 | _makeGrayscale: function (img) { 33 | if (img.getAttribute('data-grayscaled')) 34 | return; 35 | 36 | img.crossOrigin = ''; 37 | var canvas = document.createElement("canvas"); 38 | canvas.width = img.width; 39 | canvas.height = img.height; 40 | var ctx = canvas.getContext("2d"); 41 | ctx.drawImage(img, 0, 0); 42 | 43 | var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height); 44 | var pix = imgd.data; 45 | for (var i = 0, n = pix.length; i < n; i += 4) { 46 | pix[i] = pix[i + 1] = pix[i + 2] = (this.options.quotaRed * pix[i] + this.options.quotaGreen * pix[i + 1] + this.options.quotaBlue * pix[i + 2]) / this.options.quotaDivider(); 47 | } 48 | ctx.putImageData(imgd, 0, 0); 49 | img.setAttribute('data-grayscaled', true); 50 | img.src = canvas.toDataURL(); 51 | } 52 | }); 53 | 54 | L.tileLayer.grayscale = function (url, options) { 55 | return new L.TileLayer.Grayscale(url, options); 56 | }; 57 | --------------------------------------------------------------------------------