markE的回答让我大部分时间都在那里,但是我在识别我的鼠标所在的位置时遇到了一些问题。我附上了我的代码,尽管因为我使用的是OO JS,所以它的结构会有所不同:
hitImage: function() {
return (this.startX > this.imageX && this.startX < this.imageX + this.imageWidth && this.startY > this.imageY && this.startY < this.imageY + this.imageHeight);
},
handleMouseDown: function(e){
this.startX = parseInt(e.clientX - this.offsetX);
this.startY = parseInt(e.clientY - this.offsetY);
// set the drag flag
this.isDragging= this.hitImage;
},
handleMouseUp: function(e,img){
this.startX=parseInt(e.clientX-this.offsetX);
this.startY=parseInt(e.clientY-this.offsetY);
// clear the drag flag
this.isDragging=false;
this.drawImage(e,img);
},
handleMouseOut: function(e,img){
this.handleMouseUp(e,img);
},
handleMouseMove: function(e,img){
// only compute new positions if in drag
if(this.isDragging){
this.canMouseX=parseInt(e.clientX - this.offsetX);
this.canMouseY=parseInt(e.clientY - this.offsetY);
// move the image by the amount of the latest drag
var dx = this.canMouseX - this.startX;
var dy = this.canMouseY - this.startY;
this.imageX += dx;
this.imageY += dy;
// Negative image locations break the pattern in this.fillPattern
this.imageY = Math.max(0, this.imageY);
this.imageX = Math.max(0, this.imageX);
// reset the startXY for next time
this.startX = this.canMouseX;
this.startY = this.canMouseY;
this.drawImage(e,img);
}