我试图在每个客户端的屏幕上显示所有连接的客户端屏幕的鼠标光标。这样的事情:http://www.moock.org/unity/clients/uCoop/uCoop.html
我正在使用node.js在socket.io上工作。 我尝试使用mousemove上的context.drawImage在屏幕上的光标位置画一个圆圈,但即使鼠标移开并且清除屏幕使其变慢,光标仍保留在屏幕上。所以我认为,在画布上绘图并不是一个完美的解决方案,我只需要以某种方式向客户端发送鼠标坐标信息。但我不知道如何。
客户端代码段:
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 ] });
}
}
服务器端代码段:
socket.on('draw_cursor', function (data) {
io.emit('draw_cursor', { line: data.line });
});
由于 温尼
答案 0 :(得分:1)
我建议您绘制HTML元素而不是使用画布。这样,您可以为每个游标重用相同的元素,只需更新坐标即可。为此,您应该为每条draw_cursor
消息添加一个ID,以跟踪哪个元素是:
socket.on('draw_cursor', function (data) {
io.emit('draw_cursor', { line: data.line, id: socket.id });
});
然后,在您的客户端处理程序中,您找到或创建HTML元素并更新它的位置:
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;
}
现在,您只需设置cursor
元素的样式。这是一个小小的css开始:
.cursor {
position: absolute;
background: black;
width: 20px;
height: 20px;
border-radius: 10px;
}