javascript – Change the "d" attribute of the path of a curved line


I'm trying to change the "d" attribute of all lines in a specific SVG map to make straight lines curved.

d="M514 222L488 66"

Is there a universal algorithm to change any straight line with the "d" attribute (as in the example above) and get a curved line as a result?

Free translation of the Change path “d” attribute to curve the line question by @Free Lancer .


Below is how I would like to do it: for a curve (quadratic Bézier curve Q) I need to calculate the position of the control point.
In this case, it is necessary to calculate the control point in the middle of the line at distance R.

Please read the comments in the code to understand how this is done.

 // переменная для определения кривизны let R = 50; // точки исходной линии let linePoints = [ {x:514,y:222}, {x:488,y:66} ] //длина линии let length = thePath.getTotalLength(); //точка в середине линии let point = thePath.getPointAtLength(length/2); // вычислить угол линии let dy = linePoints[1].y - linePoints[0].y; let dx = linePoints[1].x - linePoints[0].x; let angle = Math.atan2(dy,dx); let cp = {//контрольная точка для Безье перпендикулярной линии к траектории x:point.x + R*Math.cos(angle + Math.PI/2), y:point.y + R*Math.sin(angle + Math.PI/2) } //новый d атрибут для path let d = `M${linePoints[0].x}, ${linePoints[0].y} Q${cp.x},${cp.y} ${linePoints[1].x}, ${linePoints[1].y}`; //установка нового "d" fnhb,enf thePath.setAttributeNS(null,"d",d)
 svg { border: 1px solid; width: 100vh; } path { stroke: black; fill: none; }
 <svg viewBox = "300 0 400 300"> <path id="thePath" d="M514, 222L488, 66" /> </svg>

Free translation of Change path “d” attribute to curve the line answer by @enxaneta .

Scroll to Top