Home > other >  Flutter canvas. How to get a ray through two points, and calculate the position through the x or y c
Flutter canvas. How to get a ray through two points, and calculate the position through the x or y c

Time:12-16

My English is not good, I'll try to explain my question as well as I can. Thank you.

I use canvas to draw.

A, B, C is on the same line. There's two points and a x/y axis value of 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

I need calculate the Offset of c if I have x/y value.

And encapsulated as a function like this:

/// @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
}

And sometime the Offset is not positive number, need to consider those conditions: https://i.bmp.ovh/imgs/2021/12/c6352f50f5dfb00d.png

My language is not English, so the description may be confusing, if I don’t describe clearly, I will continue to explain, thank you very much!

CodePudding user response:

You can try this funcion. (I am not test this code, pls try this code and show me result if it not working):

  /// @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);
  }
  • Related