Reputation: 13
I am trying to display the mouse cursors of all the connected client screen on every client's screen. Something like this : http://www.moock.org/unity/clients/uCoop/uCoop.html
I am working on socket.io using node.js. I tried drawing a circle on the cursor position on the screen using context.drawImage on mousemove but the cursor remains on the screen even after the mouse moves away and clearing the screen makes it slow. So I think, drawing on a canvas is not a perfect solution, I just need to emit the information of mouse co-ordinates to the client somehow. But I don't know how.
Client side code snippet:
socket.on('draw_cursor', function (data) {
var line = data.line;
context.beginPath();
context.fillStyle = "#000000";
context.arc(line[0].x*width, line[0].y*height, 10, 0, 2*Math.PI);
context.fill();
delay(2000);
});
function mainLoop() {
if (mouse.move && mouse.pos_prev) {
// send line to to the server
socket.emit('draw_cursor', { line: [ mouse.pos, mouse.pos_prev ] });
}
}
Server side code snippet:
socket.on('draw_cursor', function (data) {
io.emit('draw_cursor', { line: data.line });
});
Thanks Vinni
Upvotes: 0
Views: 3756
Reputation: 39223
I propose you draw HTML elements instead of using a canvas. That way, you can reuse the same element for each cursor and just update the coordinates. To do this, you should add an ID to each draw_cursor
message, to keep track of which element is which:
socket.on('draw_cursor', function (data) {
io.emit('draw_cursor', { line: data.line, id: socket.id });
});
Then, in your client handler, you find or create the HTML element and update it's position:
function getCursorElement (id) {
var elementId = 'cursor-' + id;
var element = document.getElementById(elementId);
if(element == null) {
element = document.createElement('div');
element.id = elementId;
element.className = 'cursor';
// Perhaps you want to attach these elements another parent than document
document.appendChild(element);
}
return element;
}
socket.on('draw_cursor', function (data) {
var el = getCursorElement(data.id);
el.style.x = data.line[0].x;
el.style.y = data.line[0].y;
}
Now, you just have to style the cursor
elements. Here's a little css to start with:
.cursor {
position: absolute;
background: black;
width: 20px;
height: 20px;
border-radius: 10px;
}
Upvotes: 1