我正在使用 websockets 构建一个工具,它允许多个用户在彼此的 Canvas 上“绘图”。用户在 Canvas 上绘图,包含 mousedown/mouseup 事件和坐标的对象会立即推送给其他用户。然后将其绘制在他们的 Canvas 上,从而产生让多个用户在同一个地方绘图的效果。
它的工作原理与描述的一样:您可以观看某人画东西,然后画一些东西,这些东西会出现在他们的 Canvas 中。当您与其他人同时绘制时,就会出现问题。
对于每个用户,它使用以下方法为每个用户的 Canvas 创建一个新上下文:
oekaki['canvas'] = document.getElementById('canvas');
oekaki['ctx'][unique_user_id] = oekaki['canvas'].getContext("2d");
当您与其他用户同时绘图时, Canvas 会疯狂地在您和他们的坐标之间绘制线条,尽管它使用的是不同的上下文。
为什么会这样?我是否需要做其他事情来容纳一次绘制的多条线?这样是不是不能创建多个context?
如有任何帮助,我们将不胜感激。
最佳答案
The HTML5 Canvas spec says , 对于 getContext()
:
If the getContext() method has already been invoked on this element for the same contextId, return the same object as was returned that time, and abort these steps. The additional arguments are ignored.
每个用户没有不同的上下文,它是相同的。最后一个路径位置被每个新事件改变,我猜你没有使用 beginPath
和 moveTo
来重置每个新事件的路径。尝试这样的事情:
// on some event, want to draw to (x, y) now:
var ctx = oekaki.canvas.getContext('2d');
var user = oekaki.user[unique_user_id];
ctx.beginPath();
ctx.moveTo(user.lastX, user.lastY);
ctx.lineTo(x, y);
// ctx.strokeStyle = ..., ctx.stroke(), etc, etc...
user.lastX = x;
user.lastY = y;
关于javascript - HTML Canvas : Multiple getContext plotting at same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8417318/