如何更改Leafletjs L.GridLayer的动态不透明度?
这适用于普通图层,例如:
<input id="slide" type="range" min="0" max="1" step="0.1" value="0.5" onchange="updateOpacity(this.value)">
var layer =L.tileLayer(url).addTo(map);
function updateOpacity(value) {
layer.setOpacity(value);
}
但是相同的方法不适用于定义为的画布层,例如:
L.GridLayer.CanvasCircles = L.GridLayer.extend({... or
CanvasCircles = L.GridLayer.extend({...
CanvasCircles = L.GridLayer.extend({
createTile: function (coords) {
var tile = document.createElement('canvas');
var tileSize = this.getTileSize();
tile.setAttribute('width', tileSize.x);
tile.setAttribute('height', tileSize.y);
var ctx = tile.getContext('2d');
// Draw whatever is needed in the canvas context
// For example, circles which get bigger as we zoom in
ctx.arc(tileSize.x/2, tileSize.x/2, 4 + coords.z*4, 0, 2*Math.PI, false);
ctx.fill();
return tile;
}
});
canvasCircles = function(opts) {
return new CanvasCircles(opts);
};
map.addLayer( canvasCircles() );
答案 0 :(得分:0)
由于IvanSanchez,解决方案是引用将图层启动到变量的函数。然后可以在不透明度更改函数中引用该变量。扩展原始的Leafletjs示例(http://leafletjs.com/examples/extending/extending-2-layers.html),完整代码如下:
HTML:
<input id="slide" type="range" min="0" max="1" step="0.1" value="1" onchange="updateOpacity(this.value)">
JS:
CanvasCircles = L.GridLayer.extend({
createTile: function(coords) {
var tile = document.createElement('canvas');
var tileSize = this.getTileSize();
tile.setAttribute('width', tileSize.x);
tile.setAttribute('height', tileSize.y);
var ctx = tile.getContext('2d');
// Draw whatever is needed in the canvas context
// For example, circles which get bigger as we zoom in
ctx.arc(tileSize.x / 2, tileSize.x / 2, 4 + coords.z * 4, 0, 2 * Math.PI, false);
ctx.fill();
return tile;
}
});
canvasCircles = function(opts) {
return new CanvasCircles(opts);
};
var canvasCirclesLayer = canvasCircles(); //This is what makes the difference!
map.addLayer(canvasCirclesLayer);
function updateOpacity(value) {
canvasCirclesLayer.setOpacity(value);
}