Graphics Reference
In-Depth Information
Each successive step of the chain performs one action and returns an object
for the next method. To understand what is happening, read these three
lines from left to right:
var svg = —Define the variable svg .
d3 —Call the d3 library.
.select("body") —From the d3 library, use the select method to
pick and return the object "body" on the web page.
.append("svg") —Add a new object, after all the other objects
contained in body of type svg . This returns the svg object, on which
you can now set attributes.
.attr("width",500) , .attr("height",500) —Set some
attributes associated with the svg object. In this case, svg has
attributes of width and height that are being set to the variables
width and height . Each time .attr is used, the same object is
returned, thereby allowing more attributes to be set in successively
chained methods. Note that the final item on a method chain has a
semicolon to indicate the end of the chain.
At the end of this sequence, the SVG drawing area is set up but is otherwise
empty with no content. The next five lines of D3 code create the first circle:
svg.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 75)
.attr("fill", "orange");
This example simply takes the svg variable previously defined, pointing to
the new svg object, and appends toit a new circle SVG object. This object
hasvariouscircleattributesdefined.Similarcodeisusedtomakethesecond
circle.
Running this in a browser with the Inspector window open shows the
HTML, script, and all the SVG code that was created by the script, as shown
in Figure 8-5 .
 
Search WWH ::




Custom Search