Created
August 29, 2011 15:47
SVG Patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SVG Patterns Example |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Pie Chart</title> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js"></script> | |
<style type="text/css"> | |
body { | |
font: 10px sans-serif; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var w = 400, | |
h = 400, | |
r = Math.min(w, h) / 2, | |
data = d3.range(10).map(Math.random), | |
color = d3.scale.category20(), | |
donut = d3.layout.pie().sort(d3.descending), | |
arc = d3.svg.arc().innerRadius(r * .6).outerRadius(r); | |
var vis = d3.select("body") | |
.append("svg:svg") | |
.data([data]) | |
.attr("width", w) | |
.attr("height", h); | |
// create the patterns | |
var defs = vis.append('svg:defs'); | |
var allpatterns = defs.selectAll("pattern") | |
.data(color.range()) | |
.enter().append('svg:pattern') | |
.attr('id', function(d, i) { return "pattern-" + i; }) | |
.attr('width', 16) | |
.attr('height', 16) | |
.attr('patternUnits', 'userSpaceOnUse'); | |
allpatterns | |
.append('svg:rect') | |
.attr('width', 16) | |
.attr('height', 16) | |
.attr('fill', function(d, i) { return color(i); }); | |
allpatterns | |
.append('svg:image') | |
.attr('width', 16) | |
.attr('height', 16) | |
.attr('xlink:href', 'somepattern.gif'); | |
// same as Mike's example | |
var arcs = vis.selectAll("g.arc") | |
.data(donut) | |
.enter().append("svg:g") | |
.attr("class", "arc") | |
.attr("transform", "translate(" + r + "," + r + ")"); | |
arcs.append("svg:path") | |
.attr("fill", function(d, i) { return "url(#pattern-" + i + ")"; }) | |
.attr("d", arc); | |
arcs.append("svg:text") | |
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) | |
.attr("dy", ".35em") | |
.attr("text-anchor", "middle") | |
.attr("display", function(d) { return d.value > .15 ? null : "none"; }) | |
.text(function(d, i) { return d.value.toFixed(2); }); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment