Thursday, January 12, 2012

Creating SVG groups using D3.js - an example

Creating SVG groups with D3.js

The following piece of code gives an example of how to create SVG groups using D3.js, add graphical elements to these groups and simultaneously set attributes of elements belonging to a particular group. Scroll below to see the resulting figure.

<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<title>Creating SVG groups with D3.js</title>
</head>
<body>
<div id="d3group"></div>
<script type="text/javascript">
d3image = d3.select("#d3group");
// Add SVG canvas
svgcanvas = d3image.append("svg:svg")
.attr("width", 325)
.attr("height", 250);
// Background dark gray rectangle
svgcanvas.append("svg:rect")
.attr("x",0)
.attr("y",0)
.attr("width",325)
.attr("height",250)
.style("fill", "rgb(125,125,125)");
// Add a group to the canvas
group1 = svgcanvas.append("svg:g")
.attr("stroke", "white")
.attr("stroke-width", 3)
.attr("fill", "orange");
// These attributes affect all
// graphical elements in group1.
// Add a circle to the group1
circle1 = group1.append("svg:circle")
.attr("cx", 75)
.attr("cy", 162.5)
.attr("r", 37.5);
// Add a rectangle to group1
rect1 = group1.append("svg:rect")
.attr("x",25)
.attr("y",25)
.attr("width",100)
.attr("height",75);
// Add text to group1
text1 = group1.append("svg:text")
.text("Group 1")
.attr("x", 37.5)
.attr("y", 237.5)
.style("stroke", "orange")
.style("stroke-width", 1)
.style("font-size", "150%")
.style("fill", "orange");
// Note that we can change style elements
// of specific shapes in the group. The stroke
// color of text is different than other elements in group 1.
//Add another group to the canvas
group2 = svgcanvas.append("svg:g")
.attr("stroke", "white")
.attr("stroke-width", 3)
.attr("fill", "lightgreen");
// These attributes affect all
// graphical elements in group2.
// Add a circle to the group1
circle2 = group2.append("svg:circle")
.attr("cx", 250)
.attr("cy", 62.5)
.attr("r", 37.5);
// Add a rectangle to group1
rect1 = group2.append("svg:rect")
.attr("x",200)
.attr("y",125)
.attr("width",100)
.attr("height",75);
// Add text to group2
text2 = group2.append("svg:text")
.text("Group 2")
.attr("x", 212.5)
.attr("y", 237.5)
.style("stroke", "lightgreen")
.style("stroke-width", 1)
.style("font-size", "150%")
.style("fill", "lightgreen");
// Note that we can change style elements
// of specific shapes in the group. The stroke
// color of text is different than other elements in group 2.
</script>
</body>
</html>

The above code gives:

2 comments:

  1. Thanks! I never really understood groups from other tutorials but this helped so much!

    ReplyDelete
  2. Thanks! Used this to figure out how to make an SVG with a dark background color (just add a rectangle).

    ReplyDelete