2

我无法像 SVG 中的贝塞尔曲线那样构建一条穿过所有点但不在这些点之外的曲线。

我尝试过贝塞尔曲线、二次曲线、平滑曲线和 Casteljau

这是我的示例的链接https://dotnetfiddle.net/KEqts0

不幸的是,我可以使用第 3 方进行映射。

我不想放置输出,因为那只是噪音,我附上了一张图片供参考。 在此处输入图像描述

4

1 回答 1

2

观察:最初的问题被标记为javascript。发布我的答案后,javascript标签被删除(不是由OP)。

给定一个点数组pointsRy,您需要计算贝塞尔曲线的控制点的位置。第一条和最后一条曲线是二次贝塞尔曲线。所有其他曲线都是三次贝塞尔曲线。

这是一个图像,我在其中标记点和​​通过每个点的曲线的切线。控制点是切线的起点和终点。

切线的大小是相对于点之间的距离计算的:let t = 1 / 5;更改它以更改曲率。

带有标记点的曲线

let svg = document.querySelector("svg")

let t = 1 / 5;// change this to change the curvature

let pointsRy = [[100,100],[250,150],[300,300],[450,250], [510,140],[590,250],[670,140]];

thePath.setAttribute("d", drawCurve(pointsRy));

function drawCurve(p) {

  var pc = controlPoints(pointsRy); // the control points array

  let d="";
  d += `M${p[0][0]}, ${p[0][1]}`
  
  // the first & the last curve are quadratic Bezier
  // because I'm using push(), pc[i][1] comes before pc[i][0]
  d += `Q${pc[1][1].x}, ${pc[1][1].y}, ${p[1][0]}, ${p[1][1]}`;


  if (p.length > 2) {
    // central curves are cubic Bezier
    for (var i = 1; i < p.length - 2; i++) {
      
     d+= `C${pc[i][0].x}, ${pc[i][0].y} ${pc[i + 1][1].x},${pc[i + 1][1].y} ${p[i + 1][0]},${p[i + 1][1]}`; 

    }//end for
    // the first & the last curve are quadratic Bezier
    let n = p.length - 1;
    d+=`Q${pc[n - 1][0].x}, ${pc[n - 1][0].y} ${p[n][0]},${p[n][1]}`;
  }
  return d;
}
function controlPoints(p) {
  // given the points array p calculate the control points
  let pc = [];
  for (var i = 1; i < p.length - 1; i++) {
    let dx = p[i - 1][0] - p[i + 1][0]; // difference x
    let dy = p[i - 1][1] - p[i + 1][1]; // difference y
    // the first control point
    let x1 = p[i][0] - dx * t;
    let y1 = p[i][1] - dy * t;
    let o1 = {
      x: x1,
      y: y1
    };

    // the second control point
    var x2 = p[i][0] + dx * t;
    var y2 = p[i][1] + dy * t;
    var o2 = {
      x: x2,
      y: y2
    };

    // building the control points array
    pc[i] = [];
    pc[i].push(o1);
    pc[i].push(o2);
  }
  return pc;
}
body{background:black; margin:1em;}
svg{border: 1px solid #999;}
path{fill:none; stroke:white;}
<svg viewBox="0 0 800 400">  
  <path id="thePath" stroke="white"/>
</svg>

于 2020-11-20T17:35:06.583 回答