线与点画布之间的距离

时间:2018-10-20 16:18:40

标签: javascript canvas geometry

我有一个上限和一个下限。每行包含一个起点和终点新行 x_start,y_start,x_end,y_end

然后我有一个位置x和y的矩形。而x的任何值,我都想获得上线和底线之间的垂直距离。

enter image description here

我的策略是找到每条线(顶部和底部)与假想垂直线(x,0,x,10)的交点

我使用了此代码,但它不支持无限斜率。

When(/^I enter (phone number|email)$/) do |method|
login_type = case method
        when 'phone number'
          true
        when 'email'
          false
        else
          raise("#{method} is not supported")
      end
verify_login_page(type: login_type)
aggregator = case method
             when 'phone number'
               Aggregator::PHONE
             when 'email'
               Aggregator::EMAIL
             else
               Aggregator::ALL
           end
get_and_enter_code(aggregator)
end

如何实现?

1 个答案:

答案 0 :(得分:0)

线a=(x0,y0, x1,y1)与穿过x=xp的垂直线的交点与计算x == xp的线中的y坐标相同。
a线垂直(x0 = x1)时,没有解决方案(将其绘制并查看原因)。

function getYinLine(a, xp) {
    return Math.abs(a[0].x - a[1].x) < Number.EPSILON ? undefined
        :  a[0].y + (a[1].y - a[0].y) / (a[1].x - a[0].x) * (xp - a[0].x);
}

由于行a确实是段,因此您还应该检查边界x0 <= xp <= x1

两条线之间的垂直距离是y坐标之差:

y1 = getYinLine(a, xp);
y2 = getYinLine(b, xp);
if(typeof y1 !== "undefined" && typeof y2 !== "undefined")
    dist = Math.abs(y1-y2);
else
  //do error handling
相关问题