Skip to content

Instantly share code, notes, and snippets.

@PifyZ
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PifyZ/8755653 to your computer and use it in GitHub Desktop.
Save PifyZ/8755653 to your computer and use it in GitHub Desktop.
Contrôle des évènements de la souris
class Mouse
constructor: (el) ->
@el = el
@x = 0
@y = 0
@click = null
@mtime = 0
@loose = null
document.addEventListener('mousedown', @onmousedown)
document.addEventListener('mousemove', @onmousemove)
document.addEventListener('mouseup', @onmouseup)
update: ->
@mtime++
onmouseup: (e) =>
@loose = @mtime
@click = null
onmousedown: (e) =>
@onmousemove(e)
@click = @mtime
onmousemove: (e) =>
@x = e.pageX - (if @el then @el.offsetLeft else 0)
@y = e.pageY - (if @el then @el.offsetTop else 0)
up: -> @click == null
down: -> @click != null
press: -> @click == @mtime
release: -> @loose == @mtime
(function() {
function Mouse(el) {
var self = this;
this.init = function() {
this.x = 0;
this.y = 0;
this.click = null;
this.mtime = 0;
this.el = el;
this.loose = null;
// todo : document => el ?
document.addEventListener('mousedown', this.onmousedown);
document.addEventListener('mousemove', this.onmousemove);
document.addEventListener('mouseup', this.onmouseup);
};
this.update = function() {
this.mtime++;
};
this.onmouseup = function(e) {
self.loose = self.mtime;
self.click = null;
};
this.onmousedown = function(e) {
self.onmousemove(e);
self.click = self.mtime;
};
this.onmousemove = function(e) {
var el = typeof self.el != undefined ? self.el : null;
self.x = e.pageX - (el != null ? el.offsetLeft : 0);
self.y = e.pageY - (el != null ? el.offsetTop : 0);
};
this.up = function() {
return this.click == null;
};
this.down = function() {
return this.click != null;
};
this.press = function() {
return this.click == this.mtime;
};
this.release = function() {
return this.loose == this.mtime;
};
this.init();
}
window.Mouse = Mouse;
})();
/* Utilisation
--------------- */
var mouse = new Mouse();
function update() {
if (mouse.press()) {
console.log('PRESS : ' + mouse.x + ' ; ' + mouse.y);
}
if (mouse.down()) {
console.log('DOWN : ' + mouse.x + ' ; ' + mouse.y);
}
if (mouse.release()) {
console.log('RELEASE : ' + mouse.x + ' ; ' + mouse.y);
}
if (mouse.up()) {
console.log('UP : ' + mouse.x + ' ; ' + mouse.y);
}
// Tout à la fin
mouse.update();
requestAnimationFrame(update);
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment