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
?)。
我想要做的事情是能夠分別拖動每個圓圈。