Question

I am very new to web programming. Is it possible to update a canvas element in a client's browser from server code?

If the data model that determines the canvas changes every second in the server, how can the client's browser should reflect that change?

Every client connected to the server should see the same canvas, that changes frequently.

I am trying to do this in Play with Scala.

If not canvas, what would an alternative be?

Thanks.

Was it helpful?

Solution

The technology you're looking for is websockets.

Websockets create a 2-way persistent connection between the server and client.

Websockets allow the server to broadcast messages to entire groups of connected clients so that if one player makes a move then that move is transmitted through the server to all members of the group.

Depending on the type of your server you might check out these frameworks that make websockets easier to get started with:

Socket.io + node.js: http://socket.io/

SignalR: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx

Some tips dealing with websockets + canvas:

All drawing commands must be complete--known as "atomic" (beginPath + moveTo + lineTo + stroke) or else local and remote commands will foul each other up.

But if you follow this rule then applying remote draws is simple and straight-forward:

  1. Locally receive a server broadcast containing a remote drawing command.

  2. Save that command in a queue (because the local client may be in the middle of a draw and mustn't be interrupted).

  3. When you are sure the local client is not drawing then apply the queued remote drawing commands.

Hint: it's best of all draws done by every client are done with the same stroke color and line width. Doing otherwise results in different client canvases because of the order in which the draws are applied between clients.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top