贝塞尔曲线的坐标值获取

此文只是记录!

/**
 * https://juejin.cn/post/7110589286012944391
 * 贝塞尔曲线
 */
const bezier = {
  /**
   * @desc 二阶贝塞尔
   * @param {number} t 当前百分比(0~1)
   * @param {Array} p1 起点坐标
   * @param {Array} cp 控制点
   * @param {Array} p2 终点坐标
   */
  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 当前百分比(0~1)
   * @param {Array} p1 起点坐标
   * @param {Array} cp1 控制点1
   * @param {Array} cp2 控制点2
   * @param {Array} p2 终点坐标
   */
  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;
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容