javascript - D3.js 围绕圆绘制矩形

标签 javascript d3.js

我正在尝试使用 D3.js 围绕圆绘制矩形(想象一下围绕 table 绘制椅子)。

我尝试通过设置其 x 和 y 位置然后旋转它来单独绘制每把椅子,但我运气不佳。

我认为这可能是一个好方法:

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)")

但我不知道如何进行转换、重绘,然后进行另一个转换。有什么想法吗?

最佳答案

我最终建立了使用轮换的想法。然后,我只需要温习一下我的几何形状。

首先,我在圆上找到一个点。假设您知道圆的 x 中心和 y 中心(cxcy),则在圆上查找点的方程为:

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

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

其中r是半径,a是圆上的 Angular (以弧度为单位)。

然后,我在点 (0, 0) 处绘制了每个矩形,并将它们绕圆心旋转。

这是我的解决方案最终的样子:

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)")

注意:x 减去 10 就是矩形的宽度。

关于javascript - D3.js 围绕圆绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388029/

相关文章:

javascript - 如何在 Laravel Blade 文件中 init() JS

javascript - Gradient to <td> cell according to percentage??百分比是由一些数组值计算出来的

javascript - 有没有办法在对象创建时通过字符串命名属性?

javascript - 查看 'SeekBar'的render方法

javascript - d3js - 在 exit() 转换后节点不会被删除

javascript - 处理 Mouseevent 的更有效方法

javascript - D3.js 条形图

javascript - 如何更新 D3 中的多折线图数据?

javascript - 使用 jQuery 抓取表数据并转换为无序列表

javascript - Ember.js 路由器,从 View 获取路由器