javascript - Detecting if user clicked on any circle inside canvas -
as addition previous question, now, trying detect if user clicked on created circle.
i creating node
objects when user presses keys.
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")); });
then, want know if user clicked of objects. achieve this, use simple loop:
$('#canvas').mousedown(function() { for(var = 0; < v.length; i++) { if(v[i].clicked()) { $('#clicked').html(v[i].id); v[i].update(); v[i].draw(canvas.getcontext("2d")); } } });
which not in following 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>
i don't think calculating distance wrong. think there point i've missed (maybe when returning true
, false
?).
the thing want able drag each circle separately.
a couple of errors in code:
the line:
v.push(v);
in node.draw() should moved here, after node created:
var v = new node(id); v.draw(canvas.getcontext("2d")); v.push(v);
also, mousedown event handler not getting reference event, need:
$('#canvas').mousedown(function(e) { for(var = 0; < v.length; i++) { if(v[i].clicked(e)) { $('#clicked').html(v[i].id); v[i].update(); v[i].draw(canvas.getcontext("2d")); } } });
Comments
Post a Comment