【发布时间】:2016-11-17 16:01:57
【问题描述】:
作为我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 时?)。
我想做的是能够分别拖动每个圆圈。
【问题讨论】:
标签: javascript jquery