Skip to content

Instantly share code, notes, and snippets.

@bharatbhole
Created January 14, 2012 04:53
Show Gist options
  • Save bharatbhole/1610346 to your computer and use it in GitHub Desktop.
Save bharatbhole/1610346 to your computer and use it in GitHub Desktop.
d3js_make_svgGroups
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment