40

如何检测用户何时在红色气泡内单击?

它不应该像一个方形的领域。鼠标必须真的在圆圈内:

图像

这是代码:

<canvas id="canvas" width="1000" height="500"></canvas>
<script>
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")

var w = canvas.width
var h = canvas.height

var bubble = {
  x: w / 2,
  y: h / 2,
  r: 30,
}

window.onmousedown = function(e) {
    x = e.pageX - canvas.getBoundingClientRect().left
    y = e.pageY - canvas.getBoundingClientRect().top

    if (MOUSE IS INSIDE BUBBLE) {
        alert("HELLO!")
    }
}

ctx.beginPath()
ctx.fillStyle = "red"
ctx.arc(bubble.x, bubble.y, bubble.r, 0, Math.PI*2, false)
ctx.fill()
ctx.closePath()
</script>
4

4 回答 4

60

圆,是与中心点的距离等于某个数字“R”的所有点的几何位置。

您想找到距离小于或等于我们的半径“R”的点。

二维欧几里得空间中的距离方程为d(p1,p2) = root((p1.x-p2.x)^2 + (p1.y-p2.y)^2)

检查您p与圆心之间的距离是否小于半径。

假设我有一个半径r和中心在位置(x0,y0)和一个点的圆(x1,y1),我想检查该点是否在圆内。

我需要检查是否d((x0,y0),(x1,y1)) < r转换为:

Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r

在 JavaScript 中。

现在你知道所有这些值(x0,y0)bubble.xandbubble.y(x1,y1)being xand y

于 2013-05-28T13:06:58.047 回答
44

要测试一个点是否在一个圆内,您需要确定给定点与圆心之间的距离是否小于圆的半径。

您可以比较点之间的非平方根(或静止平方)距离,而不是使用涉及使用(慢)平方根的点距离公式。如果那个距离小于半径的平方,那么你就进去了!

// x,y is the point to test
// cx, cy is circle center, and radius is circle radius
function pointInCircle(x, y, cx, cy, radius) {
  var distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy);
  return distancesquared <= radius * radius;
}

(不使用您的代码,因为我想为以后提出此问题的旁观者保留通用功能)

理解起来稍微复杂一些,但速度也更快,如果您打算在绘图/动画/对象移动循环中检查圆内点,那么您将希望以最快的方式进行。

相关JS性能测试:

http://jsperf.com/no-square-root

于 2013-05-29T16:15:50.023 回答
6

只需计算鼠标指针和圆心之间的距离,然后确定它是否在里面:

var dx = x - bubble.x,
dy = y - bubble.y,
dist = Math.sqrt(dx * dx + dy * dy);

if (dist < bubble.r) {
  alert('hello');
}

演示

如评论中所述,要消除,Math.sqrt()您可以使用:

var distsq = dx * dx + dy * dy,
rsq = bubble.r * bubble.r;

if (distsq < rsq) {
   alert('HELLO');
}
于 2013-05-28T13:08:37.610 回答
4

另一种选择(并不总是有用的意思是它只适用于(重新)定义的最后一条路径,但我将它作为一个选项提出):

x = e.pageX - canvas.getBoundingClientRect().left
y = e.pageY - canvas.getBoundingClientRect().top

if (ctx.isPointInPath(x, y)) {
    alert("HELLO!")
}

路径可以顺便说一句。是任何形状。

更多详情:
http ://www.w3.org/TR/2dcontext/#dom-context-2d-ispointinpath

于 2013-05-28T15:28:53.397 回答