在 socket.io 中的每个连接的客户端上显示光标

Displaying cursor on every connected client in socket.io

我试图在每个客户端的屏幕上显示所有连接的客户端屏幕的鼠标光标。像这样:http://www.moock.org/unity/clients/uCoop/uCoop.html

我正在 socket.io 使用 node.js。 我尝试在 mousemove 上使用 context.drawImage 在屏幕上的光标位置画一个圆圈,但即使在鼠标移开并清除屏幕后光标仍保留在屏幕上使其变慢。所以我认为,在 canvas 上绘图并不是一个完美的解决方案,我只需要以某种方式将鼠标坐标的信息发送给客户端。但是我不知道怎么办。

客户端代码片段:

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 });
});

谢谢 文尼

我建议你绘制 HTML 个元素而不是使用 canvas。这样,您就可以为每个光标重复使用相同的元素并只更新坐标。为此,您应该为每个 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;
}