loading...
Cover image for Multiuser on the Canvas

Multiuser on the Canvas

zimlearn profile image Dr Abstract ・2 min read

ZIM Socket handles multiuser without any server code! Here are examples https://zimjs.com/socket. And here is an app we just made in a morning at https://codepen.io/danzen/pen/jOrzNyp. You can see the code and fork the app on codepen.

Here is the code for a shared ball! Who doesn't like to share their balls! Okay - strike that statement.

// load in these urls
// https://zimjs.org/cdn/2.3.0/socket.io.js
// https://zimjs.org/cdn/zimserver_urls.js
// https://zimjs.org/cdn/zimsocket_1.1.js

// Make a single Ball that multiple people can drag around
// In the ZIM Frame here is the preparation and the code

const socket = new Socket(zimSocketURL, "sharedball");

// For the first parameter:
// The zimSocketURL comes from zimserver_urls.js 
// and points to the ZIM Socket server.
// This way, if we change the server, the app will still work.

// For the second parameter:
// Went to this URL https://zimjs.com/request.html 
// from the ZIM Socket page
// and requested a keyword "sharedball" for this app
// do not use a keyword that is already in use

// When the socket is ready we get this event
// It receives a data event of all the current data
// or just ask socket.
// There is also a history of any data stored in history
// like for a chat.

socket.on("ready", ()=>{
   const ball = new Circle(100, red).drag(stage);

   // We will get the lastest x and y of the ball
   // all latest values are automatically loaded by Socket
   let x = socket.getLatestValue("x");
   let y = socket.getLatestValue("y");

   // if someone has moved the ball then start at that position
   // otherwise, tell others to come where the ball is located
   if (x != null) {
      ball.loc(x,y);
   } else {
      ball.center();
      // we can set a single property like:
      // socket.setProperty("x", ball.x);
      // but each time we do it is a call to the server
      // so it is better to set multiple properties like so:
      socket.setProperties({x:ball.x, y:ball.y});
   }
   stage.update();

   // here is the event for when we receive data from others
   // so set the ball to the latest value
   // we can also grab this information from the data parameter
   socket.on("data", data=>{
      let x = socket.getLatestValue("x");
      let y = socket.getLatestValue("y");
      if (x != null) ball.loc(x,y);
      stage.update();
   });

   // send data when ball is moved
   ball.on("pressmove", ()=>{
      socket.setProperties({x:ball.x, y:ball.y});
   });

});

socket.on("error", ()=>{
   new Pane(600,300, "SORRY, COULD NOT CONNECT").show();
});
Enter fullscreen mode Exit fullscreen mode

If you have not checked out the Canvas recently - you simply must! Here is the ZIM Dev Site and some In-depth Guides by Dr Abstract including Your Guide to Coding Creativity on the Canvas.

Discussion

pic
Editor guide