Skip to content

Instantly share code, notes, and snippets.

@jeffkreeftmeijer
Created July 24, 2010 09:18
Show Gist options
  • Save jeffkreeftmeijer/488562 to your computer and use it in GitHub Desktop.
Save jeffkreeftmeijer/488562 to your computer and use it in GitHub Desktop.
.mouse{
position: absolute;
background-image: url('../images/cursor.png');
width: 15px;
height: 22px;
z-index: 100;
}
function ratelimit(fn, ms) {
var last = (new Date()).getTime();
return (function() {
var now = (new Date()).getTime();
if (now - last > ms) {
last = now;
fn.apply(null, arguments);
}
});
}
function move(mouse){
if(disabled == false){
if($('#mouse_'+mouse['id']).length == 0) {
$('body').append('<div class="mouse" id="mouse_'+mouse['id']+'"/>');
}
$('#mouse_'+mouse['id']).css({
'left' : (($(window).width() - mouse['w']) / 2 + mouse['x']) + 'px',
'top' : mouse['y'] + 'px'
})
}
}
$(document).mousemove(
ratelimit(function(e){
if (conn) {
conn.send(JSON.stringify({
'action': 'move',
'x': e.pageX,
'y': e.pageY,
'w': $(window).width(),
'h': $(window).height()
}));
}
}, 40)
);
var disabled = false,
conn;
var connect = function() {
if (window["WebSocket"]) {
$('#mouse_toggle').show();
$('#no_web_sockets').hide();
conn = new WebSocket("ws://jeffkreeftmeijer.com:8000/test");
conn.onmessage = function(evt) {
data = JSON.parse(evt.data);
if(data['action'] == 'close'){
$('#mouse_'+data['id']).remove();
} else if(data['action'] == 'move'){
move(data);
};
};
}
};
window.onload = connect;
var ws = require(__dirname + '/lib/ws'),
server = ws.createServer();
server.addListener("connection", function(conn){
conn.addListener("message", function(message){
message = JSON.parse(message);
message['id'] = conn.id
conn.broadcast(JSON.stringify(message));
});
});
server.addListener("close", function(conn){
conn.broadcast(JSON.stringify({'id': conn.id, 'action': 'close'}));
});
server.listen(8000);
@fearphage
Copy link

Suggestion: pull the cursor image inline
background-image: url('data:image/png;base64,...')

@hernan43
Copy link

When I use this code I can still see my own pointer 'drag' a bit behind before it hides behind my mouse. How do you get it to not display your own pointer?

Do you have to have the Node server send you your id so you know which mouse to not display?

@iamah
Copy link

iamah commented Aug 3, 2010

I'm intrigued by ratelimit()... If "last" value is calculated right away, then with every mousemove event the "last" will be updated? I'll have to read that a couple times to understand how it maintains the 40ms rate limit.

@azlyth
Copy link

azlyth commented May 27, 2011

I apologize if I'm wrong, but I believe it should be "socket.broadcast(...)" as opposed to "client.broadcast(...)" (lines 33 and 37 in server.js).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment