Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created November 22, 2012 10:03
Show Gist options
  • Save demonixis/4130337 to your computer and use it in GitHub Desktop.
Save demonixis/4130337 to your computer and use it in GitHub Desktop.
A simple mouseState written in JavaScript
var mouseState = {
x: 0,
y: 0,
last: { x: 0, y: 0 },
delta: { x: 0, y: 0 },
click: false,
release: true,
drag: false,
updatePositions: function (event) {
this.last.x = this.x;
this.last.y = this.y;
this.x = event.offsetX;
this.y = event.offsetY;
},
updateClickStates: function (event) {
if (event.type == "mousedown") {
this.click = true;
this.release = false;
}
else if (event.type == "mousemove") {
if (this.click) {
this.drag = true;
}
else {
this.drag = false;
}
}
else if (event.type == "mouseup") {
this.click = false;
this.release = true;
this.drag = false;
}
},
updateDelta: function () {
this.delta.x = Math.floor(this.x - this.last.x);
this.delta.y = Math.floor(this.y - this.last.y);
},
update: function (event) {
this.updatePositions(event);
this.updateClickStates(event);
this.updateDelta();
},
toString: function () {
var positions = "POSITIONS:\nx: " + this.x + " | y: " + this.y + "\nlast.x: " + this.last.x + " | last.y: " + this.last.y + "\ndelta.x: " + this.delta.x + " | delta.y: " + this.delta.y;
var buttons = "BUTTONS:\nclick: " + this.click + " | release: " + this.release + " | drag: " + this.drag;
return ("-------\n" + positions + "\n" + buttons + "\n-------\n");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment