简体   繁体   English

如何在D3中使用现有的svg元素?

[英]How should I use an existing svg element in D3?

I have an svg being generated using Snap.svg. 我有一个使用Snap.svg生成的svg。 I want to use this svg in d3 now. 我现在想在d3中使用此svg。 How can I do this ? 我怎样才能做到这一点 ?

Code --> 代码->

var s =  Snap(400,400);
s.attr({

    "id" : "chart"

})

var rect = s.rect(100,100,100,100)

and then selecting it in d3 : --> 然后在d3中选择它:->

var mysvg = d3.select("#chart")

alert(mysvg)

the alert method above gives output -- > object SVGSVGElement] 上面的alert方法给出输出->对象SVGSVGElement]

I am unable to figure out how to make use of this "mysvg" element to show the svg on d3 chart. 我无法弄清楚如何利用此“ mysvg”元素在d3图表上显示svg。

Yes, D3 and Snap do compliment each other and you can use them together. 是的,D3和Snap互为补充,可以一起使用。 I like to add shapes to a group before targeting them in either D3 or Snap but you can target the shapes directly. 我想先将形状添加到组中,然后再在D3或Snap中定位它们,但是您可以直接定位形状。 Sometimes its easier working with shapes instead of group since they have x/y properties and you don't have to worry about working with transform and matrix but as soon as you have complex group, its easier to move a group of shapes then move them each individually. 有时,使用形状而不是分组更容易,因为它们具有x / y属性,并且您不必担心使用变换和矩阵,但是一旦您拥有复杂的组,移动一组形状然后移动它们就更容易每个单独。

In your case, you have a simple rect that is contained in your "mysvg" which is the root svg. 就您而言,您的“ mysvg”(即根svg)中包含一个简单的rect。 You can add elements either through Snap or D3. 您可以通过Snap或D3添加元素。 You probably want to target that rect and do something with it like make it grow based on some data value. 您可能想要针对该rect并对其进行处理,例如使其根据某些数据值增长。 In which case, you might consider giving it an id or class name. 在这种情况下,您可以考虑为其指定ID或类名。

var rect = s.rect(100,100,100,100)
rect.attr({"id", "bar0"}); // assuming you'd create many bars and give them ids dynamically 
rect.attr({"class", "bar"}); 

then in D3, you can target that bar directly 然后在D3中,您可以直接定位该酒吧

var bar = mysvg.select("#bar0");
bar.attr("height", 60);
bar.attr("width", 20); 

I've create a jsfiddle based on your question but using game elements instead of a chart - same principles apply ;-D 我根据您的问题创建了一个jsfiddle,但使用游戏元素代替了图表-应用相同的原理;-D

jsfiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM