Drawing Objects around an SVG Circle with D3.js

For my upcoming wedding reception, I built an application that lets a guest view the table and chair they have been assigned. I’m using D3.js to draw the tables and chairs. Our particular layout required both round and rectangle tables. Drawing chairs around the rectangle tables was fairly easy. The real challenge was drawing chairs around a circle table. Here is the solution I came up with:

1. Create two concentric circles.

We will use the inner circle to represent the table and will draw the chairs on the outer circle.


var svg = d3.select('svg');
var originX = 200;
var originY = 200;
var innerCircleRadius = 40;
var outerCircleRadius = 60;

var table = svg.append("circle").attr({
    cx: originX,
    cy: originY,
    r: innerCircleRadius,
    fill: "white",
    stroke: "black"
});

var outerCircle = svg.append("circle").attr({
    cx: originX,
    cy: originY,
    r: outerCircleRadius,
    fill: "none",
    stroke: "black"
});

step-1

2. Find the point at 12 o’clock on the outer circle.

We can find the point on the north edge of the circle using Trigonometry.


var chairOriginX = originX + ((outerCircleRadius) * Math.sin(0));
var chairOriginY = originY - ((outerCircleRadius) * Math.cos(0));

step-2

3. Draw the chair at 12 o’clock.

The origin of the chair should be the point on the outer circle.


var chairWidth = 20;
var chair = svg.append("rect").attr({
    x: chairOriginX - (chairWidth / 2),
    y: chairOriginY - (chairWidth / 2),
    width: chairWidth,
    opacity: 1,
    height: 20,
    fill: "none",
    stroke: "blue"
});

step-3

4. Rotate the chair around the origin of the circle.

Now that we have our chair drawn at the top of the circle, we can rotate it around the origin of the circle to nicely position it like a chair at a table.


chair.attr("transform", "rotate(45, 200, 200)");

step-4

Voila! We have a round table with a chair drawn appropriately outside of it.

step-5

If you are looking for another way to achieve the same result, you can draw the chair at the origin of the circle, translate it out of the circle, and then rotate it.

All of the code from this blog post can be found on this JSFiddle.