且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML Canvas:多个getContext同时绘制

更新时间:2023-11-09 21:37:16

HTML5 Canvas规范说 getContext()


如果对于同一contextId,已经在这个元素
上调用了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 以重置每个新事件的路径。尝试这样的代替:

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 and moveTo to reset the path on each new event. Try something like this instead:

// 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;