简体   繁体   中英

How should I use an existing svg element in D3?

I have an svg being generated using Snap.svg. I want to use this svg in d3 now. 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 : -->

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

alert(mysvg)

the alert method above gives output -- > object SVGSVGElement]

I am unable to figure out how to make use of this "mysvg" element to show the svg on d3 chart.

Yes, D3 and Snap do compliment each other and you can use them together. I like to add shapes to a group before targeting them in either D3 or Snap but you can target the shapes directly. 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.

In your case, you have a simple rect that is contained in your "mysvg" which is the root svg. You can add elements either through Snap or D3. You probably want to target that rect and do something with it like make it grow based on some data value. In which case, you might consider giving it an id or class name.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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