Day47: Adding forces in D3

Posted by csiu on April 12, 2017 | with: 100daysofcode,

In continuation of the pursuit to make my personal website more cool. I built on yesterday’s D3 star shape (example 3).

The code for this little project is found here.

Star

The code for the star is referred from Dillie-O’s How to draw a star with SVG and Javascript. To make it so that all stars are not orientated the same, a random rotation is added.

var rot = 2 * Math.PI * Math.random();

var pointX = centerX + Math.cos(i * angle + rot) * r;
var pointY = centerY + Math.sin(i * angle + rot) * r;

To specify the coordinates for the points in a star, trigonometry is used.


Force-directed

The code for the forces is referred from Mike Bostock’s Force-Directed Symbols example. There were a few things I changed, but the main thing was the “random shapes” are now all stars. This was done by modifying the vis.selectAll("path") chunk to:

vis.selectAll("polygon")
    .data(nodes)
  .enter().append("polygon")
    .attr("points", function(d) {
      return CalculateStarPoints(100, 100, 5, d.size, d.size / 2);
    })
    .call(force.drag);

which adds my stars and enables them to be dragged.