我认为您期望它像 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 方法重绘圆时,事件侦听器应该响应新的坐标。