检测用户是否点击圈子内 [英] Detect if user clicks inside a circle

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

问题描述

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



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





这里是代码:

 < canvas id =canvaswidth =1000height =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。



您要查找距离小于或等于R的点,我们的(p1,p2)= root((p1.x-p2.x)^(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)* )+(y1-y0)*(y1-y0)) r 

在JavaScript中。



知道所有这些值(x0,y0) bubble.x bubble.y (x1,y1) x code>。


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:

Here's the code:

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

解决方案

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

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

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

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

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.

I'd need to check if d((x0,y0),(x1,y1)) < r which translates to:

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

In JavaScript.

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

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

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