如何使用svg<clipPath>剪裁Leaflet GeoJSON图层

3
根据官方教程,我现在可以加载并显示本地geoJSON文件中的所有多边形。我计划使用自定义轮廓路径剪切新创建的SVG图层。我从一个圆开始作为clipPath的子元素,该圆是通过Leaflet的L.circle创建的,以避免坐标投影。基于官方示例的主要代码如下:
// Create a circle outline
var clipcircle = new L.circle([34.5, -95.5], {radius: 300000, className: 'outline'}).addTo(map);
// Create <defs> and <clippath> elements using jquery
$('svg').prepend('<defs><clipPath id="myclip"></clipPath></defs>');
// Move the <path> element of clipcircle from <g> to <clipPath>
$('path.outline').appendTo('#myclip');
// Add CSS clip-path attribute to all svg groups
$('g').css('clip-path', 'url(#myclip)');
// load and show polygons from geoJSON
var geojson = L.geoJSON(statesData, {
        style: style,
        onEachFeature: onEachFeature
    }).addTo(map);
map.fitBounds(geojson.getBounds());

代码的效果符合预期,但是clipPath没有起作用。只有圆形内部的区域应该被显示,但是除了圆形以外的所有多边形仍然显示在页面上,如下图所示:

不移动的添加圆形

1个回答

1
问题在于创建clipPath新元素时,jquery将元素名称转换为小写(如规范中所述),因为html标记不应区分大小写(但似乎clipPath确实区分大小写)。
要解决这个问题,您需要回到本机DOM操作并选择svg,并使用createElementNS创建元素。
var svg = document.getElementsByTagName('svg')[0]

//Create a new element of clipPath
var clipPathChild = document.createElementNS('http://www.w3.org/2000/svg', "clipPath");

//set an ID (I went lazy and continued with jquery)
$(clipPathChild).attr('id', 'myclip')

//append new node to the svg
svg.appendChild(clipPathChild);

//the "outline" class was added previously to the geojson we want to use as mask 
// add the outline to clip the new node just created
$('path.outline').appendTo('#myclip');

//set the ID of the clip-path to the main feature to clip
$('path').attr('clip-path', 'url(#myclip)');

这个解决方案对我有用,因为您的代码在理论上是正确的,但由于jquery在创建新元素时进行了简单的小写转换,所以它失败了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接