HTML Canvas:同时绘制多个 getContext
我正在使用 websockets 构建一个工具,该工具允许多个用户在彼此的画布上“绘图”。用户在画布上绘图,包含 mousedown/mouseup 事件和坐标的对象会立即推送给其他用户。然后将其绘制在他们的画布上,这给出了多个用户在同一个地方绘图的效果。
它的工作原理如下:您可以观看某人画一些东西,然后画一些将出现在他们的画布中的东西。当你和其他人同时画画时,就会出现问题。
对于每个用户,它使用以下方式为每个用户的画布创建一个新的上下文:
oekaki['canvas'] = document.getElementById('canvas');
oekaki['ctx'][unique_user_id] = oekaki['canvas'].getContext("2d");
当您与另一个用户同时绘图时,画布会在您和他们的坐标之间疯狂地绘制线条,尽管它使用不同的上下文。
为什么会这样呢?我是否需要做其他事情来容纳同时绘制的多条线?难道就不能用这种方式创建多个上下文吗?
任何帮助将不胜感激。
I'm building a tool using websockets which allows multiple users to "draw" on each others' canvases. The user draws on a canvas, and an object containing mousedown/mouseup events and coordinates is pushed to other users instantaneously. This is then plotted on their canvases, which gives the effect of having multiple users drawing in the same place.
It works as described: you can watch somebody draw something, then draw something which will appear within their canvas. The problem occurs when you draw at the same moment as somebody else.
For each user, it creates a new context for each user's canvas using:
oekaki['canvas'] = document.getElementById('canvas');
oekaki['ctx'][unique_user_id] = oekaki['canvas'].getContext("2d");
When you draw at the same moment as another user, the canvases madly draw lines between your and their coordinates, despite it using the different contexts.
Why is this the case? Do I have to do something else to accommodate multiple lines being plotted at once? Is it not possible to create multiple contexts in this way?
Any help would be most appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HTML5 Canvas 规范说,对于
getContext()
:每个用户没有不同的上下文,它们是相同的。最后一个路径位置会被每个新事件更改,我猜您没有使用
beginPath
和moveTo
来重置每个新事件的路径。尝试这样的事情:The HTML5 Canvas spec says, for
getContext()
:You don't have a different context per user, it's the same one. The last path position is being altererd by each new event, and I'm guessing you're not using
beginPath
andmoveTo
to reset the path on each new event. Try something like this instead:我怀疑您的用户正在使用相同的上下文。我建议收集传入的绘图请求并将其组合到一种绘制方法中,该方法在适当的时候构建画布内容。
I suspect that it is the same context your users are drawing onto. I suggest to collect the incoming drawing requests and combine it in one paint method that builds the canvas contents when appropriate.