HTML Canvas:多个getContext同时绘制 [英] HTML Canvas: Multiple getContext plotting at same time

查看:1118
本文介绍了HTML Canvas:多个getContext同时绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用websockets构建一个工具,允许多个用户绘制彼此的画布。用户在画布上绘制,并且包含mousedown / mouseup事件和坐标的对象被即时推送到其他用户。然后绘制在他们的画布上,这产生了多个用户绘制在同一地方的效果。

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.

推荐答案

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;

这篇关于HTML Canvas:多个getContext同时绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆