椭圆绘图在d3中使用弧

时间:2016-02-13 09:35:11

标签: jquery d3.js svg jquery-svg

我想用弧线绘制一个椭圆。我做了圆圈,但我不能用椭圆做。 请帮我椭圆

圈子代码

var π = Math.PI,
    τ = 2 * π,
    n = 500;

var width = 300,
    height = 200,
    outerRadius = width / 2 - 20,
    innerRadius = outerRadius - 20;

d3.select("svg").append("g")
    .attr("transform", "translate(" + width / 2 + "," + 200	 + ")")
  .selectAll("path")
    .data(d3.range(0, τ, τ / n))
  .enter().append("path")
    .attr("d", d3.svg.arc()
        .outerRadius(outerRadius)
        .innerRadius(innerRadius)
        .startAngle(function(d) { return d; })
        .endAngle(function(d) { return d + τ / n * 1.1; }))
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="960" height="960"></svg>

1 个答案:

答案 0 :(得分:2)

D3 arc()函数仅生成圆弧段。它实际上会根据您提供的内半径和外半径生成实体形状的轮廓。

将圆弧转换为椭圆弧的唯一方法是以不同方式缩放水平和垂直尺寸。见下文。

var π = Math.PI,
    τ = 2 * π,
    n = 500;

var width = 300,
    height = 200,
    outerRadius = 1,
    innerRadius = 0.85,
    cx = 200,
    cy = 150;

d3.select("svg").append("g")
    .attr("transform", "translate(" + cx + "," + cy + ") scale(" + (width/2) + "," + (height/2) + ")")
  .selectAll("path")
    .data(d3.range(0, τ, τ / n))
  .enter().append("path")
    .attr("d", d3.svg.arc()
        .outerRadius(outerRadius)
        .innerRadius(innerRadius)
        .startAngle(function(d) { return d; })
        .endAngle(function(d) { return d + τ / n * 1.1; }))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="960" height="960"></svg>

缺点当然是不均匀的缩放会随着弧的厚度而变化。也许这对你没问题。如果没有,你应该扩展你的问题,进一步详细说明你实际想要实现的目标。