0
作为我的previous question的补充,现在,我试图检测用户是否在任何创建的圆圈上单击。检测用户是否点击画布内的任意圆圈
我在用户按下按键时创建了Node
对象。
jQuery(document).ready(function() {
$('#canvas').attr('height', $('#canvas').css('height'));
$('#canvas').attr('width', $('#canvas').css('width'));
var x = -1;
var y = -1;
var V = [];
function Node(id) {
var _this = this;
// constructor
(function() {
_this.x = x || null;
_this.y = y || null;
_this.id = id || null;
_this.clicked = false;
})();
this.draw = function(ctx) {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.font = '16pt Calibri';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.fillText(id, x, y+3);
ctx.stroke();
V.push(v);
}
this.clicked = function(e) {
var xDif = e.offsetX - _this.x;
var yDif = e.offsetY - _this.y;
var d = Math.sqrt((xDif*xDif) + (yDif*yDif));
if(d < 20) return true;
else return false;
}
this.update = function() {
_this.x = x;
_this.y = y;
}
}
var overCanvas = false;
$('#canvas').mouseover(function() {
overCanvas = true;
});
$('#canvas').mouseleave(function() {
overCanvas = false;
});
$("#canvas").mousemove(function(e) {
x = e.offsetX;
y = e.offsetY;
$('#status').html(x + ', ' + y);
});
$(document).keypress(function(e) {
if (!overCanvas) {
return;
}
var id = -1;
switch(e.keyCode)
{
case 97:
case 49: id = '1'; break
case 98:
case 50: id = '2'; break;
case 99:
case 51: id = '3'; break;
case 100:
case 52: id = '4'; break;
case 101:
case 53: id = '5'; break;
case 102:
case 54: id = '6'; break;
case 120:
case 88: id = 'x'; break;
default: return;
}
var v = new Node(id);
v.draw(canvas.getContext("2d"));
});
然后,我想知道用户是否点击了任何对象。要做到这一点,我用一个简单的循环:
$('#canvas').mousedown(function() {
for(var i = 0; i < V.length; i++)
{
if(V[i].clicked())
{
$('#clicked').html(V[i].id);
V[i].update();
V[i].draw(canvas.getContext("2d"));
}
}
});
这并不做以下HTML什么:
<body>
<h2 id="status">0, 0</h2>
<h2 id="clicked">init</h2>
<canvas style="width: 1000px; height: 1000px; border:1px ridge green;" id="canvas">
</canvas>
</body>
我不认为我在计算距离错。我认为有一点我错过了(也许当返回true
和false
?)。
我想要做的事情是能够分别拖动每个圆圈。