node-red-contrib-jwht-map/worldmap/leaflet/TileLayer.Grayscale.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-04-01 18:31:07 +08:00
/*
* L.TileLayer.Grayscale is a regular tilelayer with grayscale makeover.
*/
L.TileLayer.Grayscale = L.TileLayer.extend({
options: {
2019-03-12 05:08:53 +08:00
quotaRed: 21,
quotaGreen: 71,
quotaBlue: 8,
quotaDividerTune: 0,
quotaDivider: function() {
return this.quotaRed + this.quotaGreen + this.quotaBlue + this.quotaDividerTune;
}
2016-04-01 18:31:07 +08:00
},
initialize: function (url, options) {
2019-03-12 05:08:53 +08:00
options = options || {}
options.crossOrigin = true;
2016-04-01 18:31:07 +08:00
L.TileLayer.prototype.initialize.call(this, url, options);
2019-03-12 05:08:53 +08:00
this.on('tileload', function(e) {
this._makeGrayscale(e.tile);
});
2016-04-01 18:31:07 +08:00
},
2019-03-12 05:08:53 +08:00
_createTile: function () {
var tile = L.TileLayer.prototype._createTile.call(this);
tile.crossOrigin = "Anonymous";
return tile;
2016-04-01 18:31:07 +08:00
},
2019-03-12 05:08:53 +08:00
_makeGrayscale: function (img) {
if (img.getAttribute('data-grayscaled'))
return;
img.crossOrigin = '';
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
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();
2016-04-01 18:31:07 +08:00
}
2019-03-12 05:08:53 +08:00
ctx.putImageData(imgd, 0, 0);
img.setAttribute('data-grayscaled', true);
img.src = canvas.toDataURL();
2016-04-01 18:31:07 +08:00
}
});
L.tileLayer.grayscale = function (url, options) {
return new L.TileLayer.Grayscale(url, options);
};