Multiuser Drawing

Invite your friends to this page to draw collaboratively.

// global variables
var c;
var pubnub;
var uniqueid;

function setup() 
{
  // canvas size
  createCanvas(400, 400);

  // random color
  c = color(random(255), random(255), random(255));

  // create a unique_id
  uniqueid = PUBNUB.uuid()

  // initialize pubnub
  pubnub = PUBNUB.init(
  {
    publish_key   : 'pub-c-98b7b004-d2ab-4ccb-a9e9-b45893cdda11',
    subscribe_key : 'sub-c-535f47ea-cfb1-11e3-8297-02ee2ddab7fe',
    uuid: uniqueid
  });

  // subscribe to drawing channel
  pubnub.subscribe(
  {
    channel : "drawing",
    message: handleMessage
  });
}

function draw() 
{
  if(mouseIsPressed)
  {
    // publish drawing data
    pubnub.publish(
    {
      channel: 'drawing',
      message: {
        x1: pmouseX,
        y1: pmouseY,
        x2: mouseX,
        y2: mouseY,
        c: c,
        uniqueid: uniqueid
      }
    });
	
    // draw what the user is drawing immediately
    stroke(c);
    strokeWeight(3);
    line(pmouseX, pmouseY, mouseX, mouseY);
  }
}

// when we receive a message from pubnub
function handleMessage(message) 
{
  // draw lines on screen if the user is someone else
  if(message.uniqueid != uniqueid)
  {
    stroke(message.c);
    strokeWeight(3);
    line(message.x1, message.y1, message.x2, message.y2);
  }
}

This uses p5.js and PubNub. Sign up for a PubNub account and replace the publish_key and the subscribe_key to build your own interactive project.