Sharing Variables Between Canvases

How to share variables between seperate instances of Processing.js

Move your mouse over the Canvases above. They are sharing a common MouseX variable.

Creating dynamic user interfaces with Processing would be impossible if you could not share variables between instances. Sharing variables allows you to create interface elements that "talk" to eachother. If you were developing a learning application that explained gemoetry, you could aid the learner by creating interactive examples with Processing, asking the user questions as they learned. If you wanted to track the user's progress with a rich interactive chart, you would need some level of communication between the Processing scripts.

void setup(){
  size(320,240);
  strokeWeight(12);
  stroke(0);  
}

int internalMouseX=0;
window.Processing.data.globalMouseX=0;

void mouseMoved() {  
  window.Processing.data.globalMouseX=mouseX; 
}

void draw(){      
  background(100);          
  internalMouseX = window.Processing.data.globalMouseX;
    
  pushMatrix();                       
    translate(width/2, height/2);    
    rotate(radians(internalMouseX));
    rect(-40,-40,80,80);
  popMatrix();      
}

Code for the example above.

Technique: If you view-source on this page, you will notice a very small line of JavaScript in the head. window.Processing.data = {}; This creates a global Processing.data object in the window, allowing me to create and set any variables I want to at run-time. I can do this from within any Processing script and retrive them in any other script using the Processing.data object attached to window.

In the code example: For every mouseMoved() event, the mouseX value is set in the window.Processing.data.globalMouseX variable. This variable has been created in the window.Processing.data object at run-time, making it very easy to share data without having to make tedious declarations that would lock down the scope of communication between the Canvas scripts.

Then for every draw() frame, that same value is returned from the window.Processing.data space and applied to rotation radian of the rect(). The code for each canvas is essentially the same, I have only changed the strokeWidth() and the background(colour) to demonstrate that they are in fact two different Processing instances running.