扑canvas。如何通过两点得到一条射线,通过另一点的x或y坐标计算位置

Flutter canvas. How to get a ray through two points, and calculate the position through the x or y coordinates of the other point

我用canvas画画

A、B、C在同一条线上。有两个点和一个 x/y 轴值 pointC:

Offset pointA = Offset(100, 200);
Offset pointB = Offset(200, 400);
double pointCx = 300;

Offset pointC = calculateOffsetByX(pointA, pointB, pointCx);

https://i.bmp.ovh/imgs/2021/12/0a7ee73b12749799.png

如果我有 x/y 值,我需要计算 c 的偏移量。

并封装成这样的函数:

/// @param [pointStart] start point of line
/// @param [point2] second point of line
/// @param [x] the position x of point need to calculate
/// @return Offset of the point on line
Offset calculateOffsetByX(Offset pointStart, Offset point2, double x){
  // TODO
}
/// @param [pointStart] start point of line
/// @param [point2] second point of line
/// @param [y] the position y of point need to calculate
/// @return Offset of the point on line
Offset calculateOffsetByY(Offset pointStart, Offset point2, double y){
  // TODO
}

而且有时候Offset不是正数,需要考虑那些情况: https://i.bmp.ovh/imgs/2021/12/c6352f50f5dfb00d.png

你可以试试这个功能。 (我没有测试这段代码,请尝试这段代码,如果它不起作用,请告诉我结果):

  /// @param [pointStart] start point of line
  /// @param [point2] second point of line
  /// @param [x] the position x of point need to calculate
  /// @return Offset of the point on line
  Offset calculateOffsetByX(Offset pointStart, Offset point2, double x){
    //y =  ax + b
    final a = (pointStart.dy - point2.dy)/(pointStart.dx - point2.dx);
    final b = pointStart.dy - a*pointStart.dx;
    return Offset(x, a*x +b);
  }
  /// @param [pointStart] start point of line
  /// @param [point2] second point of line
  /// @param [y] the position y of point need to calculate
  /// @return Offset of the point on line
  Offset calculateOffsetByY(Offset pointStart, Offset point2, double y){
    //y =  ax + b
    final a = (pointStart.dy - point2.dy)/(pointStart.dx - point2.dx);
    final b = pointStart.dy - a*pointStart.dx;
    return Offset((y - b)/a, y);
  }