貝塞爾曲線的坐標(biāo)值獲取

此文只是記錄!

/**
 * https://juejin.cn/post/7110589286012944391
 * 貝塞爾曲線
 */
const bezier = {
  /**
   * @desc 二階貝塞爾
   * @param {number} t 當(dāng)前百分比(0~1)
   * @param {Array} p1 起點(diǎn)坐標(biāo)
   * @param {Array} cp 控制點(diǎn)
   * @param {Array} p2 終點(diǎn)坐標(biāo)
   */
  quad(t, p1, cp, p2) {
    const [x1, y1] = p1;
    const [cx, cy] = cp;
    const [x2, y2] = p2;
    const x = Math.pow(1 - t, 2) * x1 + 2 * (1 - t) * t * cx + Math.pow(t, 2) * x2;
    const y = Math.pow(1 - t, 2) * y1 + 2 * (1 - t) * t * cy + Math.pow(t, 2) * y2;
    return [x, y];
  },
  /**
   * @desc 三階貝塞爾
   * @param {number} t 當(dāng)前百分比(0~1)
   * @param {Array} p1 起點(diǎn)坐標(biāo)
   * @param {Array} cp1 控制點(diǎn)1
   * @param {Array} cp2 控制點(diǎn)2
   * @param {Array} p2 終點(diǎn)坐標(biāo)
   */
  cubic(t, p1, cp1, cp2, p2) {
    const [x1, y1] = p1;
    const [x2, y2] = p2;
    const [cx1, cy1] = cp1;
    const [cx2, cy2] = cp2;
    const x = Math.pow(1 - t, 3) * x1 + 3 * Math.pow(1 - t, 2) * t * cx1 + 3 * (1 - t) * Math.pow(t, 2) * cx2 + Math.pow(t, 3) * x2;
    const y = Math.pow(1 - t, 3) * y1 + 3 * Math.pow(1 - t, 2) * t * cy1 + 3 * (1 - t) * Math.pow(t, 2) * cy2 + Math.pow(t, 3) * y2;
    return [x, y];
  },
};

// const canvas = document.querySelector('canvas');
// canvas.width = 400;
// canvas.height = 400;
// const ctx = canvas.getContext('2d');
// const startPoint = [200, 400];
// const endPoint = [200, 0];
// const controlPoint = [300, 200];
// ctx.beginPath();
// ctx.moveTo(startPoint[0], startPoint[1]);
// // i 每次增加的約小,精度越高
// for (let i = 0; i < 1; i += 0.1) {
//   const [x, y] = bezier.quad(i, startPoint, controlPoint, endPoint);
//   ctx.lineTo(x, y);
// }
// ctx.stroke();

export function getBezierList(startPoint, endPoint, controlPoint) {
  // const startPoint = [200, 400];
  // const endPoint = [200, 0];
  // const controlPoint = [300, 200];
  let list = [];
  for (let i = 0; i < 1; i += 0.1) {
    const [x, y] = bezier.quad(i, startPoint, controlPoint, endPoint);
    list.push({ x, y });
  }
  return list;
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容