Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw an svg arc using d3 knowing 3 points on the arc

Tags:

d3.js

I would like to draw an arc using d3.js functions starting at point A via point B and end it at point C.

enter image description here

I would like to know if there is a way using d3 functions like eg. d3.radialLine() or d3.path().arcTo() maybe in combination with other d3 functions without having to code the maths for anything.

like image 400
Risingson Avatar asked May 06 '17 21:05

Risingson


1 Answers

There isn't a path generator built in d3 to do that - you could grab the one I wrote for swoopy-drag though:

//convert 3 points to an Arc Path 
function calcCirclePath(points){
  var a = points[0].pos
  var b = points[2].pos
  var c = points[1].pos

  var A = dist(b, c)
  var B = dist(c, a)
  var C = dist(a, b)

  var angle = Math.acos((A*A + B*B - C*C)/(2*A*B))

  //calc radius of circle
  var K = .5*A*B*Math.sin(angle)
  var r = A*B*C/4/K
  r = Math.round(r*1000)/1000

  //large arc flag
  var laf = +(Math.PI/2 > angle)

  //sweep flag
  var saf = +((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0]) < 0) 

  return ['M', a, 'A', r, r, 0, laf, saf, b].join(' ')
}

function dist(a, b){
  return Math.sqrt(
    Math.pow(a[0] - b[0], 2) +
    Math.pow(a[1] - b[1], 2))
}
like image 53
Adam Pearce Avatar answered Nov 10 '22 09:11

Adam Pearce