Skip to content

Instantly share code, notes, and snippets.

@KoGor
Created August 13, 2014 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KoGor/c6838e2800c8dd8eaf96 to your computer and use it in GitHub Desktop.
Save KoGor/c6838e2800c8dd8eaf96 to your computer and use it in GitHub Desktop.
Dynamic tiles clipping

Dynamic tiles clipping on Leaflet maps. There is no sync when zooming for now, but I hope to add it after Leafle 0.8 will be available. There are some bugs in webkit based browsers (blink of whole unclipped layer just after zoom) and no auto reclipping of layer when we recalculate clip-path.

Filters and patterns working great, no bugs detected.

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
stamenUrl = 'http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png',
attrib = '&copy; Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> | <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
main = L.tileLayer(stamenUrl, {maxZoom: 18, attribution: attrib}),
map = new L.Map('map', {
layers: [main],
center: [55.7501, 37.6687],
zoom: 11
}),
overlay = L.tileLayer(osmUrl).addTo(map);
overlay.getContainer().style.display = "none";
main.getContainer().style.filter = "url(#sepia)";
main.getContainer().style.WebkitFilter = "url(#sepia)";
//Convert Leaflet geometries to D3 geometries
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
};
//Initialize SVG layer in Leaflet (works for leaflet-0.7.3)
map._initPathRoot()
var transform = d3.geo.transform({point: projectPoint}),
path = d3.geo.path().projection(transform);
var svg = d3.select(".leaflet-overlay-pane").select("svg"),
// add "leaflet-zoom-hide" class to SVG container for turning off zoom
defs = svg.append("defs"),
filterBlur = defs.append("filter").attr("id", "blur"),
filterGrayscale = defs.append("filter").attr("id", "grayscale"),
clipPath = defs.append("clipPath").attr("id", "clipPath");
//Blur filter params
filterBlur.append("feGaussianBlur").attr("stdDeviation", 2);
filterGrayscale.append("feColorMatrix").attr("type", "saturate").attr("values", 0);
//Leaflet.draw stuff
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
position: 'topleft',
polygon: {
title: 'Draw a sexy polygon!',
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#fff',
weight: 10,
opacity: 0.8,
fill: false
},
showArea: true
},
rectangle: {
shapeOptions: {
color: '#fff',
weight: 10,
opacity: 0.8,
fill: false
}
},
polyline: false,
marker: false,
circle: false
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
var geoJSONlayer = layer.toGeoJSON();
geoJSONlayer.properties.id = 'l' + layer._leaflet_id;
clipPath.append("path")
.attr("id", 'l' + layer._leaflet_id)
.datum(geoJSONlayer)
.attr("d", path)
.attr("fill", "white")
.attr("opacity", 0.95); //change opacity to control masking
clip();
});
map.on('draw:deleted', function (e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
clipPath.select("#l" + layer._leaflet_id).remove();
});
clip();
});
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
var geoJSONlayer = layer.toGeoJSON();
clipPath.select("#l" + layer._leaflet_id)
.datum(geoJSONlayer)
.attr("d", path);
});
clip();
});
//Clipping or masking change code accordingly
function clip() {
var clippingPaths = clipPath.selectAll("path");
clippingPaths.attr("d", path);
if (clippingPaths.size() > 0) {
overlay.getContainer().style.display = "inline";
overlay.getContainer().style.clipPath = 'url(#clipPath)';
overlay.getContainer().style.WebkitClipPath = 'url(#clipPath)';
} else {
overlay.getContainer().style.display = "none";
overlay.getContainer().style.clipPath = 'none';
overlay.getContainer().style.WebkitClipPath = 'none';
};
};
//Some extra controls
var filterDropdown = L.Control.extend({
options: {
position: 'topright'
},
onAdd: function (map) {
// create the control container with a particular class name
var container = L.DomUtil.create('div', 'dropdown-control');
// ... initialize other DOM elements, add listeners, etc.
container.innerHTML = '<label>filter: <select><option selected>none</option><option>grayscale</option><option>saturate</option><option>hue_rotate</option><option>luminance_mask</option></select></label>';
L.DomEvent
.on(container.firstChild.firstElementChild, 'change', function(e) {
var filterStyle = main.getContainer().style.filter;
if (this.value != 'none') {
overlay.getContainer().style.filter = 'url(#'+ this.value + ')';
overlay.getContainer().style.WebkitFilter = 'url(#'+ this.value + ')';
} else {
overlay.getContainer().style.filter = 'none';
overlay.getContainer().style.WebkitFilter = 'none';
};
});
return container;
}
});
map.addControl(new filterDropdown());
var patternDropdown = L.Control.extend({
options: {
position: 'topright'
},
onAdd: function (map) {
// create the control container with a particular class name
var container = L.DomUtil.create('div', 'dropdown-control');
// ... initialize other DOM elements, add listeners, etc.
container.innerHTML = '<label>pattern: <select><option selected>none</option><option>diagonalHatch</option><option>diagonalHash</option></select></label>';
L.DomEvent
.on(container.firstChild.firstElementChild, 'change', function(e) {
if (this.value != 'none') {
drawControl.setDrawingOptions({
polygon: {
shapeOptions: {
color: '#fff',
weight: 10,
opacity: 0.8,
fill: true,
fillOpacity: 0.5,
fillColor: 'url(#'+ this.value + ')'
},
},
rectangle: {
shapeOptions: {
color: '#fff',
weight: 10,
opacity: 0.8,
fill: true,
fillOpacity: 0.5,
fillColor: 'url(#'+ this.value + ')'
}
}
})
} else {
drawControl.setDrawingOptions({
polygon: {
shapeOptions: {
color: '#fff',
fill: false
},
showArea: true
},
rectangle: {
shapeOptions: {
color: '#fff',
weight: 10,
opacity: 0.8,
fill: false
}
}
});
};
});
return container;
}
});
map.addControl(new patternDropdown());
var blurControl = L.Control.extend({
options: {
position: 'topright'
},
onAdd: function (map) {
// create the control container with a particular class name
var container = L.DomUtil.create('div', 'blur-control');
// ... initialize other DOM elements, add listeners, etc.
container.innerHTML = '<label><input type="checkbox" name="blur" value="clear">BLUR</label>';
L.DomEvent
.on(container.firstChild.firstElementChild, 'change', function(e) {
if (this.value == 'clear') {
svg.selectAll("g").selectAll('path').attr("filter", "url(#blur)");
this.value = 'blured';
} else {
svg.selectAll("g").selectAll('path').attr("filter", "none");
this.value = 'clear';
};
clip();
});
return container;
}
});
map.addControl(new blurControl());
//Update on move and viewreset
map.on('move', clip);
map.on('viewreset', clip);
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8 />
<title>Dynamic tile clipping and more</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.2/leaflet.draw.css' rel='stylesheet' />
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.2/leaflet.draw.js'></script>
<style>
.blur-control {
background-color: #fff;
box-shadow: rgba(0, 0, 0, 0.65) 0px 1px 5px 0px;
}
.dropdown-control {
box-shadow: rgba(0, 0, 0, 0.65) 0px 1px 5px 0px;
background-color: #fff;
}
.dropdown-control > label {
background-color: #fff;
border-radius: 4px;
padding: 4px;
display: block;
}
.blur-control > label {
background-color: #fff;
border-radius: 4px;
cursor: pointer;
display: block;
padding: 4px;
}
.blur-control input {
vertical-align: bottom;
}
</style>
</head>
<body>
<div id="map" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>
<script src="dtc.js"></script>
<!--SVG filters for map container -->
<svg>
<defs>
<filter id="grayscale">
<feColorMatrix type="saturate" values="0"/>
</filter>
<filter id="saturate">
<feColorMatrix type="saturate" values="10"/>
</filter>
<filter id="hue_rotate">
<feColorMatrix type="hueRotate" values="180"/>
</filter>
<filter id="luminance_mask">
<feColorMatrix type="luminanceToAlpha"/>
</filter>
<filter id="sepia">
<feColorMatrix
type="matrix"
values=".343 .669 .119 0 0
.249 .626 .130 0 0
.172 .334 .111 0 0
.000 .000 .000 1 0 "/>
</filter>
<pattern id="diagonalHatch" width="10" height="10" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
<line x1="0" y1="0" x2="0" y2="10" style="stroke:white; stroke-width:10" />
</pattern>
<pattern id="diagonalHash" width="10" height="10" patternTransform="rotate(45 0 0)" patternUnits="userSpaceOnUse">
<g>
<line x1="0" y1="0" x2="0" y2="10" style="stroke:white; stroke-width:5" />
<line x1="5" y1="0" x2="10" y2="0" style="stroke:white; stroke-width:5" />
</g>
</pattern>
</defs>
</svg>
</body>
</html>
The MIT License (MIT)
Copyright (c) 2014 [KoGor](https://github.com/KoGor)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment