Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate line to make a half-circle/arc in d3

Tags:

svg

d3.js

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));
like image 388
Wex Avatar asked Dec 11 '25 13:12

Wex


2 Answers

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) + ")");
like image 164
Wex Avatar answered Dec 13 '25 19:12

Wex


Have you looked at the arc section?

like image 24
SuperMykEl Avatar answered Dec 13 '25 17:12

SuperMykEl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!