找出一个点是否在一条线上 [英] Finding if a point is on a line

查看:160
本文介绍了找出一个点是否在一条线上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在HTML5 Canvas中画了一条线:

Let's say I have a line drawn as so in HTML5 Canvas:

...
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x1,y1);
ctx.closePath();
...

我想知道鼠标停止事件是否发生在这一行,我有这样的代码:

I want to find out if the mouse down event happened on this line, and I have code like this:

var handleMouseDown = function(e) {
  var coords = translateCoords(e.x,e.y);
  ...
  if (ctx.isPointInPath(coords.x, coords.y) {
    ...

现在,这个代码适用于圆和矩形,但不适用于行。我有两个问题:

Now, this code works fine in the case of circles & rectangles, but not for lines. I have 2 questions:


  1. 我的想法是,或许在一行上调用closePath()是不正确的。问题 - 如何检查鼠标停止事件是否发生在这一行?

  1. My thinking is that perhaps calling closePath() on a line itself is incorrect. Question - how can I check if the mouse down event happened on this line?

如何扩展此项以查找鼠标停止事件是否发生在附近该行?

How can I extend this to find if the mouse down event happened near the line?


推荐答案

第一步是找到点到线上的正常投影。这实际上很简单:从点开始距离1到目标,并指向目标2,并分别称它们为D1和D2。然后计算 D1 +(D2-D1)/ 2 。这是到目标的距离从点1开始的线上的投影点。

The first step is to find the normal projection of the point onto the line. This is actually quite simple: take the distance from point 1 to the target, and point 2 to the target, and call them D1 and D2 respectively. Then calculate D1+(D2-D1)/2. This is the distance to the projected point on the line from point 1.

您现在可以找到该点,并获得从该点到焦油的距离如果距离为零,那么目标正好在线上。如果距离小于5,则目标距离小于5px,依此类推。

You can now find that point, and get the distance from that point to the target. If the distance is zero, then the target is exactly on the line. If the distance is less than 5, then the target was less than 5px away, and so on.

编辑:图片胜过千言万语。这是一个图表:

A picture is worth a thousand words. Here's a diagram:

图表http://adamhaskell.net/img/ schematic.png

(事后看来,可能应该让那些圆圈成为不同的颜色......另外,紫色线应该垂直于线条AB。用蓝线怪我可怕的目标!)

(In hindsight, probably should have made those circles a different colour... Also, the purple line is supposed to be perpendicular to line AB. Blame my terrible aim with the blue line!)

这篇关于找出一个点是否在一条线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆