HTMLcanvas:两个客户端在同一时间写入

我在使用nodejs作为客户端之间的服务器实现在线 HTML5 Canvas时遇到了麻烦。

一个单独的用户可以单独绘画而没有问题,但是当另一个客户端进来并且同时绘画时 ,会发生以下情况: 两个客户端的HTML5 Canvas问题

Client1是第一个客户端鼠标的(X,Y)位置, Client2是第二个客户端的(X,Y)位置。 所以当第二个客户端绘制的时候, 我的程序在这两个点之间画了一条线

在这里,您可以浏览客户机JS代码,其中绘图函数负责绘制从nodejs服务器接收到的数据:

App.draw = function(x, y, type, color, clear) { if(clear != true) { App.ctx.strokeStyle = color; if (type === "dragstart") { App.ctx.beginPath(); //alert("Me muevo a X: " + x + " e Y: " + y); return App.ctx.moveTo(x, y); } else if (type === "drag") { App.ctx.lineTo(x, y); return App.ctx.stroke(); } else { return App.ctx.closePath(); } } else { // Store the current transformation matrix App.ctx.save(); // Use the identity matrix while clearing the canvas App.ctx.setTransform(1, 0, 0, 1, 0, 0); App.ctx.clearRect(0, 0, App.canvas.width, App.canvas.height); // Restore the transform App.ctx.restore(); } }; 

当你共享相同的path时,path将包括一组混合的点,包括两个客户端。

为了避免这种情况,你可以使用两种技术之一:

解决scheme1

每收到一个新点(每个客户端),完成一个单独的行程。 这会将当前path减less到单个笔划:

 App.ctx.beginPath(); App.ctx.moveTo(oldX, oldY); /// previous point for this client App.ctx.lineTo(x, y); App.ctx.strokeStyle = color; App.ctx.stroke(); 

解决scheme2

使用两个层叠在彼此顶部的canvas。 为每个客户端分配一个图层。 这样他们是完全独立的,如果需要的话,你可以将它们合并为一个,如果你需要将结果保存为图像:

HTML:

 <div class="wrapper"> <canvas id="client1" ... ></canvas> <canvas id="client2" ... ></canvas> </div> 

CSS:

 .wrapper { position:relative; } .wrapper > canvas { position:absolute; left:0; top:0; } 

然后使用分配给每个客户的不同上下文variables。 一种方法可以是:

 App.ctx = [ctx1, ctx2]; 

然后在你的函数中使用参数client作为索引(在这种情况下是0或1):

 App.draw = function(client, x, y, type, color, clear) { if(clear != true) { App.ctx[client].strokeStyle = color; if (type === "dragstart") { App.ctx[client].beginPath(); //alert("Me muevo a X: " + x + " e Y: " + y); return App.ctx[client].moveTo(x, y); } else if (type === "drag") { App.ctx[client].lineTo(x, y); App.ctx[client].stroke(); /// this has no return value return; } else { App.ctx[client].closePath(); return } } else { // Store the current transformation matrix App.ctx[client].save(); // Use the identity matrix while clearing the canvas App.ctx[client].setTransform(1, 0, 0, 1, 0, 0); App.ctx[client].clearRect(0, 0, App.canvas.width, App.canvas.height); // Restore the transform App.ctx[client].restore(); } }; 

希望这可以帮助。