更改路径“ d”属性以弯曲线

时间:2020-03-18 16:55:35

标签: javascript svg

我正在尝试更改某些SVG贴图中所有线的“ d”属性,以使直线直线弯曲。

d="M514 222L488 66"

是否存在任何通用算法来更改任何straigt线的“ d”属性(如以上所述)并获得曲线?

1 个答案:

答案 0 :(得分:1)

这就是我的操作方式:对于曲线(二次贝塞尔曲线Q),我需要计算控制点的位置。在这种情况下,我希望控制点位于直线的中间,距离为R。

请阅读代码中的注释以了解它。

// a variable to define the curvature 
let R = 50;
// the points of the original line
let linePoints = [
  {x:514,y:222},
  {x:488,y:66}
]
//the length of the line
let length = thePath.getTotalLength();
//a point in the middle of the line
let point = thePath.getPointAtLength(length/2);
// calculate the angle of the line
let dy = linePoints[1].y - linePoints[0].y;
let dx = linePoints[1].x - linePoints[0].x;
let angle = Math.atan2(dy,dx);


let cp = {//control point for the bézier as a perpendicular line to thePath
  x:point.x + R*Math.cos(angle + Math.PI/2),
  y:point.y + R*Math.sin(angle + Math.PI/2)
}

//the new d attribute for the path
let d = `M${linePoints[0].x}, ${linePoints[0].y} Q${cp.x},${cp.y} ${linePoints[1].x}, ${linePoints[1].y}`;
//set the new d attribute
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>