3

I'm trying to create a half circle in d3. Using cardinal interpolation produces a path that is close to what I want, but isn't quite "circular" enough. How can I write my own interpolator to better round this path, or is there a better method?

Here is what I have so far: http://jsfiddle.net/Wexcode/jEfsh/

<svg width="300" height="500">
    <g id="g-1"></g>
    <g id="g-2"></g>
</svg>​

JS:

var curved = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("cardinal")
    .tension(0);
var straight = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("linear")
    .tension(0);

var points = [{x: 70, y: 52.5}, {x: 250, y: 250}, {x: 70, y: 447.5}];

d3.select("#g-1").append("path").attr("d", curved(points));

d3.select("#g-2").append("path").attr("d", straight(points));
SuperMykEl
  • 613
  • 3
  • 15
Wex
  • 15,539
  • 10
  • 64
  • 107

2 Answers2

8

See: How to calculate the SVG Path for an arc (of a circle)


The problem with using d3.arc() to create curved lines is that it layers two lines on top of each other. See: https://stackoverflow.com/a/11595157/522877

d3.svg.line.radial() has significantly more control when it comes to creating arcs and circles.

Here is an example of how to create a circle: http://jsfiddle.net/Wexcode/CrDUy/

var radius = 100,
    padding = 10,
    radians = 2 * Math.PI;

var dimension = (2 * radius) + (2 * padding),
    points = 50;

var angle = d3.scale.linear()
    .domain([0, points-1])
    .range([0, radians]);

var line = d3.svg.line.radial()
    .interpolate("basis")
    .tension(0)
    .radius(radius)
    .angle(function(d, i) { return angle(i); });

var svg = d3.select("body").append("svg")
    .attr("width", dimension)
    .attr("height", dimension)
.append("g");

svg.append("path").datum(d3.range(points))
    .attr("class", "line")
    .attr("d", line)
    .attr("transform", "translate(" + (radius + padding) + ", " + (radius + padding) + ")");
Community
  • 1
  • 1
Wex
  • 15,539
  • 10
  • 64
  • 107
1

Have you looked at the arc section?

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
SuperMykEl
  • 613
  • 3
  • 15
  • That ended up being what I decided to use for this. I think I'd still like to know how I would go about doing this with a custom interpolator, if possible. – Wex Jun 29 '12 at 06:49
  • The problem with using d3.arc() to create curved lines is that it layers two lines on top of each other. See: http://stackoverflow.com/a/11595157/522877 – Wex Jul 23 '12 at 17:18
  • 1
    Makes sense. Like the example and what you did with `stroke-dasharray` – SuperMykEl Jul 23 '12 at 18:52