これがDOM APIのように機能することを期待していると思います。キャンバス コンテキスト オブジェクトは、ピクセルのグリッド上にオブジェクトを描画するためのメソッドのバンドルにすぎません。ピクセルのグリッドは、保存される唯一の実際の状態情報です。座標を保持する正方形または長方形のオブジェクトはありません。地図上に四角形と円をスプラッティングするための単なるメソッド。その情報の変更を維持して対応することは、DIY であるか、それを行うライブラリを調べる必要があります。
ただし、jQuery を使用してオンザフライでジェネリック オブジェクトの新しいイベントを書き込んだりリッスンしたりできます。
var someObj = {};
//bind - unfortunate choice for the generic listening method
$(someObj).bind('HiSomeObj',function(){ alert('hi, whoever triggered this event on me'); });
$(someObj).trigger('HiSomeObj'); //'hi, whoever triggered this event on me'
//note how in the following trigger below how I add properties to the event object
これを利用した大雑把な DIY アプローチを次に示します。
//your constructor object - assumes 16px diameter (mostly reusing your code)
function imgCircleObjConstructor16px(xArg, yArg){
var imgCircle = new Image(),
//following 2 are var defs and public for convenience
diameter = this.diameter = 16, //hard-coded for now
coords = this.coords = [xArg,yArg],
that = this; //locks down reference to instance for use in JQ
imgCircle.src = "circle.png";
this.draw = function(x,y){
//some function that clears canvas or resets context for redraws
clearCanvasOrContext();
toolboxContext.drawImage(imgCircle, x, y);
this.coords = [x,y];
}
$('#canvas').mousedown(function(e) {
var mouseXY = canvas.getMousePos(e);
if( mouseXY.x >= coords[0]) && mouseXY.x <= coords[0]+diameter &&
mouseXY.y >= coords[1] && mouseXY.y <= coords[1] ){
//trigger custom events with JQ 'trigger' method
//can't use 'this' because it refers to the jq object for #canvas here
$(that).trigger('circleBoundingBoxClicked', { someProperty:'optional' } );
//note: second arg in trigger func serves no purpose
//just provided as an example of adding properties to event objects
}
}
//might as well tell the circle to draw itself when the object is instantiated:
this.draw();
}
var myCircle = new imgCircleObjConstructor16px(16,32);
//listen to custom events with 'bind' method
$(myCircle).bind('circleBoundingBoxClicked', function(e){
var circleObj = e.target; //JQ puts object args from the $ func under target property
alert('Circle Bounding box at x: '+circleObj.coords[0]+', y:'+circleObj.coords[1]
+' was clicked. someProperty value: ' + e.someProperty);
//After you fix whatever syntax goofs I didn't test for, this should alert when clicked:
//'Circle Bounding box at x: 15, y:32 was clicked. someProperty value: optional'
} );
myCircle.draw メソッドを使用して円を再描画すると、イベント リスナーは新しい座標に応答する必要があります。