简体   繁体   中英

D3.js Drawing rectangles around a circle

I'm trying to use D3.js to draw rectangles around a circle (think of drawing chairs around a table).

I've tried drawing each chair individually by setting it's x and y position and then rotating it, but I haven't had much luck.

I thought this might be a good approach:

group = container.append("g")
table = group.append("circle").
  attr("cx", 100).
  attr("cy", 100).
  attr("r", 60).
  attr("fill", "#FFF").
  attr("stroke", "#b8b8b8").
  attr("stroke-width", "2")
group
  .append("rect")
  .attr("x", 90)
  .attr("y", 10)
  .attr("width", 20)
  .attr("height", 20)
group.attr("transform", "rotate(30, 100, 100)")

But I can't figure out how to make a transformation, redraw, and then make another transformation. Any ideas?

I ended up building upon my idea of using a rotation. Then, I just had to brush up a little on my geometry.

First, I find a point on the circle. The equation for finding a point on the circle, given you know the center-x and center-y ( cx and cy ) of the circle, is:

x = cx + ( r * sin( a ))

y = cx + ( r * cos( a ))

Where r is radius and a is the angle on the circle in radians.

Then, I drew every rectangle at the point (0, 0) and rotated them around the center of the circle.

Here is what my solution ended up looking like:

radians = (Math.PI * 0) / 180.0
x = 100 + (70 * Math.sin(radians))
y = 100 + (70 * Math.cos(radians))

for i in [0..360] by 30
 container
  .append("rect")
  .attr("x", x - 10)
  .attr("y", y)
  .attr("width", 20)
  .attr("height", 20)
  .attr("transform", "rotate(#{i}, 100, 100)")

Note: Subtracting 10 from x accounts for the width of the rectangle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM