检测用户是否在圆圈内点击

检测用户是否在圆圈内点击

本文介绍了检测用户是否在圆圈内点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测用户何时点击红色气泡?

How can I detect when the user clicks inside the red bubble?

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

It should not be like a square field. The mouse must be really inside the circle:

这是代码:

<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>


推荐答案

圆圈,是所有点的几何位置其距离中心点的距离等于一些数字R。

A circle, is the geometric position of all the points whose distance from a central point is equal to some number "R".

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

You want to find the points whose distance is less than or equal to that "R", our radius.

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

The distance equation in 2d euclidean space is d(p1,p2) = root((p1.x-p2.x)^2 + (p1.y-p2.y)^2).

检查您的 p之间的距离,圆圈的中心小于半径。

Check if the distance between your p and the center of the circle is less than the radius.

假设我有一个圆圈,半径 r 并且位于(x0,y0)和点(x1,y1)的位置,我想检查一下这个点是否在圈内。

Let's say I have a circle with radius r and center at position (x0,y0) and a point (x1,y1) and I want to check if that point is in the circle or not.

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

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

在JavaScript中。

In JavaScript.

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

Now you know all these values (x0,y0) being bubble.x and bubble.y and (x1,y1) being x and y.

这篇关于检测用户是否在圆圈内点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:31