Skip to content

Instantly share code, notes, and snippets.

@balint42
Forked from mbostock/.block
Last active May 17, 2016 23:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balint42/32845e181cf3ab28ff77 to your computer and use it in GitHub Desktop.
Save balint42/32845e181cf3ab28ff77 to your computer and use it in GitHub Desktop.

D3 example cartoonized with comic.js.

Inspired by this Paper.js example, this demonstrates animated rounded rectangles (svg:rect elements with "rx" and "ry" attributes). The data associated with each rectangle is its center position and rotation angle in degrees. Each tick of the animation, the rectangles drift towards the mouse location and rotate slightly. Built with D3.js using SVG.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://balint42.github.io/libs/pathseg.js"></script>
<script src="http://balint42.github.io/libs/comic.min.js"></script>
<script>
var mouse = [480, 250],
count = 0;
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var g = svg.selectAll("g")
.data(d3.range(25))
.enter().append("g")
.attr("transform", "translate(" + mouse + ")");
g.append("rect")
.attr("rx", 6)
.attr("ry", 6)
.attr("x", -12.5)
.attr("y", -12.5)
.attr("width", 25)
.attr("height", 25)
.attr("transform", function(d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; })
.style("fill", d3.scale.category20c());
g.datum(function(d) {
return {center: [0, 0], angle: 0};
});
COMIC.init({ ffc: 0.1, ff:1.5 });
svg.magic();
svg.on("mousemove", function() {
mouse = d3.mouse(this);
});
d3.timer(function() {
count++;
g.attr("transform", function(d, i) {
d.center[0] += (mouse[0] - d.center[0]) / (i + 5);
d.center[1] += (mouse[1] - d.center[1]) / (i + 5);
d.angle += Math.sin((count + i) / 10) * 7;
return "translate(" + d.center + ")rotate(" + d.angle + ")";
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment