[英]Convert an SVG element to a g element using d3.js
I am using D3 in a page where my objective is to superimpose two groups of paths : I have the earth coastlines as a background map (imported from a GeoJSON file), and I want to superimpose an old map on it, which is a separate SVG : http://bl.ocks.org/bperel/9943623/250fc9af2e09bf176f6d510e0b59fe643d792287 我在一个页面中使用D3,该页面的目的是叠加两组路径:我将地球海岸线作为背景地图(从GeoJSON文件导入),并且希望在其上叠加旧地图,这是一个单独的地图SVG: http : //bl.ocks.org/bperel/9943623/250fc9af2e09bf176f6d510e0b59fe643d792287
The SVG loading went well, however I would like my two maps to be included inside the same SVG element : it will be easier if I want the maps to be panned or zoomed. SVG的加载进展顺利,但是我希望将两个地图包含在同一个SVG元素中:如果希望平移或缩放地图,这会更容易。 The issue here is that the external SVG has a specific viewbox, so if I move its <g> elements to the other SVG, the coordinates get messy.
这里的问题是外部SVG具有特定的视图框,因此,如果将其<g>元素移动到另一个SVG,则坐标会变得混乱。 Hence my question : is there a way to convert the 2nd SVG to a <g> element that I could include in the first SVG ?
因此,我的问题是:有没有办法将第二个SVG转换为可以包含在第一个SVG中的<g>元素? Maybe d3 knows how to do that but I couldn't find such a tool in the documentation.
也许d3知道该怎么做,但是我在文档中找不到这样的工具。
If you are going to zoom/pan the superimposed SVG's, Include both svg's in a <g>
container element and attach zoom behavior to the <g>
container. 如果要缩放/平移叠加的SVG,请将两个 svg 都包含在
<g>
容器元素中,并将缩放行为附加到<g>
容器。
Essentually, you will have: 从本质上讲,您将拥有:
<svg id=topSVG>
<g id=container>
<svg id=projection1>
....
</svg>
<svg id=projection2>
....
</svg>
</g>
</svg>
Below is a snippet relating to my mouswheel zoom for d3: 以下是与我的d3摩沙轮缩放有关的摘要:
var myZoom=d3.behavior.zoom().scaleExtent([.1, 1000]).on("zoom", mouseWheelZoom)
function callZoomBehavior()
{
//---attach to root svg---
d3.select("#"+SVGId)
.call(myZoom)
//---reset from previous file call---
myZoom.translate([0,0])
myZoom.scale(1)
PrevScale=1
}
var PrevScale //--previous scale event---
function mouseWheelZoom()
{
//--place in d3 object--
var zoomG=d3.select("#topZoomG")
if(PrevScale!=d3.event.scale) //--transition on scale change--
{
zoomG.transition().attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
}
else //--no transition on pan---
{
zoomG.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
}
PrevScale=d3.event.scale
}
originalSVG
= the SVG element you want to clone and convert into g element quasiClone
= the result of that parentOfClone
= parent below you want to put your new g element originalSVG
=您要克隆并转换为g元素的SVG元素quasiClone
=该parentOfClone
=父元素的结果,您要在其中放置新的g元素
var quasiClone = parentOfClone.append("g");
for (var i=0; i<originalSVG.childNodes.length; i++){
var child = originalSVG.childNodes[i];
var childClone = child.cloneNode(true);
quasiClone.node().appendChild(childClone);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.