Skip to content

Instantly share code, notes, and snippets.

@zellyn
Created October 31, 2012 16:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zellyn/3987890 to your computer and use it in GitHub Desktop.
Save zellyn/3987890 to your computer and use it in GitHub Desktop.
Even more xkcd-style graphs, with SVG filters
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>xkcd-style graphs</title>
<style type="text/css">
svg {
stroke: black;
stroke-width: 3;
}
.axis path {
fill: none;
}
text, h1 {
font-family: "Comic Sans MS";
stroke: none;
}
</style>
</head>
<body>
<h1>xkcd-style graphs</h1>
<svg height="200" width="300">
<pattern id="hatch00" patternUnits="userSpaceOnUse"
x="0" y="0" width="10" height="10">
<path d="M3,0 l7,7 l0,-2 l-5,-5 l-2,0 M0,7 l3,3 l2,0 l-5,-5 l0,2"
style="fill:blue;stroke:none;"/>
</pattern>
<pattern id="hatch01" patternUnits="userSpaceOnUse"
x="0" y="0" width="10" height="10">
<path d="M7,0 l-7,7 l0,-3 l4,-4 l3,0 M10,7 l-3,3 l-3,0 l6,-6 l0,3"
style="fill:red;stroke:none;"/>
</pattern>
<filter id="my-filter">
<feTurbulence type="fractalNoise" baseFrequency="0.05" result="noise" />
<feDisplacementMap scale="5" xChannelSelector="R" yChannelSelector="G"
in="SourceGraphic" in2="noise" />
</filter>
</svg>
<script src="http://d3js.org/d3.v2.js"></script>
<script>
var graph = d3.select("svg")
.append("g")
.attr("filter", "url(#my-filter)");
// Shape data
var rect_data = [
{x: 200, y: 30},
{x: 60, y: 30}
];
var circle_data = [
{cx: 120, cy: 80, r: 45},
{cx: 250, cy: 100, r: 25},
{cx: 100, cy: 110, r: 35},
];
// Axes
var xScale = d3.scale.linear().range([50, 275]);
var yScale = d3.scale.linear().range([170, 25]);
var xaxis = d3.svg.axis()
.scale(xScale)
.ticks(5);
var yaxis = d3.svg.axis()
.scale(yScale)
.ticks(5)
.orient("left");
graph.append("g")
.attr({
class: "axis",
transform: "translate(" + [0, 170] + ")"
})
.call(xaxis);
graph.append("g")
.attr({
class: "axis",
transform: "translate(" + [50, 0] + ")"
})
.call(yaxis);
// Message
graph.append("text")
.text("Click the shapes")
.attr({
x: 70,
y: 150,
});
// Rotate between shape data entries
var rotator = function(data) {
var index = 0;
return function() {
index = (index + 1) % data.length;
d3.select(this)
.transition()
.attr(data[index])
.duration(1000);
}
}
// A rectangle
graph.append("rect")
.attr({
width: 60,
height: 130,
rx: 3,
fill: "url(#hatch00)"
})
.attr(rect_data[0])
.on("click", rotator(rect_data));
// A circle
graph.append("circle")
.attr("fill", "url(#hatch01)")
.attr(circle_data[0])
.on("click", rotator(circle_data));
var f1 = function() {
document.getElementsByTagName("feTurbulence")[0]
.setAttribute("seed", Math.random() * 100);
setTimeout(f1, 50);
};
</script>
<br />
<a href="#" onClick="f1()">Animate</a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment