sup*_*per 34 html javascript events canvas click
如何检测用户何时点击红色气泡?
它不应该像一个方形场.鼠标必须在圆圈内:
这是代码:
<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>
Run Code Online (Sandbox Code Playgroud)
Ben*_*aum 52
圆是所有点的几何位置,其距中心点的距离等于某个数字"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
Run Code Online (Sandbox Code Playgroud)
在JavaScript中.
现在你知道所有这些值(x0,y0)是bubble.x和bubble.y和(x1,y1)是x和y.
Sim*_*ris 33
要测试点是否在圆内,您需要确定给定点与圆心之间的距离是否小于圆的半径.
而不是使用涉及使用(慢)平方根的点距离公式,您可以比较点之间的非平方根(或静止平方)距离.如果那个距离小于半径的平方,那么你就进去了!
// 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;
}
Run Code Online (Sandbox Code Playgroud)
(不使用你的代码,因为我希望保持这个功能一般适用于后来提出这个问题的旁观者)
理解这一点稍微复杂一些,但它也更快,如果你打算在绘图/动画/对象移动循环中检查圆点,那么你会想要以最快的方式做到这一点.
相关的JS性能测试:
http://jsperf.com/no-square-root
只需计算鼠标指针和圆心的距离,然后确定它是否在内:
var dx = x - bubble.x,
dy = y - bubble.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < bubble.r) {
alert('hello');
}
Run Code Online (Sandbox Code Playgroud)
正如所提到的意见,消除Math.sqrt()您可以使用:
var distsq = dx * dx + dy * dy,
rsq = bubble.r * bubble.r;
if (distsq < rsq) {
alert('HELLO');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21454 次 |
| 最近记录: |