HTML5 canvas: combine

Now I am developing a chat program for drawing using an HTML5 canvas, and I encounter a problem when two or more users use the same canvas at the same time.

Canvas has only one instance for each property, only one strokeStyle, one fillStyle, etc. When two users use the same canvas; chaos.

I tried to use more canvases with the same positioning, but when and how to exchange data between two canvases is a problem.

Does anyone know of any other ways to do this or how can I properly exchange data between canvases?

EDIT:

I think I did not say this clearly enough. Now I have a canvas, messages from the server through socket.io, different drawing requests. When the user moves his mouse to draw a line, the canvas now gets lineWidth, strokeStyle, globalOpacity. However, since there can only be one artist on a canvas at a time, drawing requests from the server, including another artist, cannot be drawn at the same time. If we have enough users, the picture will not be free.

I am ready to write a queue or something like that to implement a function, but there may be another way to do this.

+6
source share
1 answer

Each client needs to send drawing commands to the server. The server must send commands to all clients. You need a method that receives messages and draws them.

eg. if the user can set attributes such as, for example, โ€œstroke sizeโ€ and color, you also need to pass these changes.

You need to register mouse listeners for users. They should call drawing methods, for example. drawMoveTo and drawLineTo , as well as buffer commands along the same path so that you can translate the full path in messages to other clients.

Examples of messages may include:

 {"clientId": 36, "penSize": 8, "color": "blue"} {"clientId": 36, "command": {"moveTo", "x": 48, "y": 12}, "path": [{"moveTo", "x": 48, "y": 12}]} {"clientId": 36, "command": {"lineTo", "x": 52, "y": 24}, "path": [{"lineTo", "x": 52, "y": 24}, {"moveTo", "x": 48, "y": 12}]} {"clientId": 36, "command": {"lineTo", "x": 47, "y": 36}, "path": [{"lineTo", "x": 47, "y": 36}, {"lineTo", "x": 52, "y": 24}, {"moveTo", "x": 48, "y": 12}]} 

You can have a data structure to track "strokeAttributes" for each user. Then, when you get a message like moveTo or lineTo , you look at clientId to get the stroke attributes, for example. penSize and color , then you call the same methods that call when the local user draws, for example. drawMoveTo and drawLineTo .

The draw methods must use different strokes and attributes depending on which client the message comes from (or the mouselistener). This will change a lot if multiple users draw at the same time.

I would recommend that you do communication using WebSockets or perhaps socket.io .

Here is a good article with code for an application similar to what you are asking for A multi-user drawing panel built in with Pure JavaScript / HTML5 / Canvas

+7
source

Source: https://habr.com/ru/post/903510/


All Articles