HTML Canvas: Multiple getContext plotting at same time

前端 未结 2 892
-上瘾入骨i
-上瘾入骨i 2021-01-12 07:19

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

相关标签:
2条回答
  • 2021-01-12 07:42

    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.

    0 讨论(0)
  • 2021-01-12 07:58

    The HTML5 Canvas spec says, for 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.

    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;
    
    0 讨论(0)
提交回复
热议问题