a port of the Processing Visualization Language
Name

/* @pjs globalKeyEvents */ directive

Examples
bypass.pde:
	
/* @pjs globalKeyEvents="true"; */

sketch.pde:
     
int linepos;

void setup()
{
  size(200,200);
  noLoop();
  linepos = height/2;
}

void draw()
{
  line(0,linepos,width,linepos);
}
    
interface Javascript {}
Javascript javascript=null;
void bindJavascript(Javascript js) { javascript=js; }

// due to every browser implementing key events differently,
// proper keyhandling requires knowing whether this
// sketch is running under Processing or under Processing.js
void keyPressed()
{
  if( (javascript==null && key=='+' && keyCode==61) ||
      (javascript!=null && (key==187 || key==119))) {
    // if someone types a "+", draw the line lower
    linepos++; 
    redraw(); 
  }
  else if( (javascript==null && key=='-' && keyCode==45)
      || (javascript!=null && (key==189 || key==115))) {
    // if someone types a "-", draw the line higher
    linepos--; 
    redraw(); 
  }
}

sketch.html:

<html>
<head>
  <script type="text/javascript" src="processing.js"></script>
  <script type="text/javascript">
  // bind javascript to all Processing instances
  function bindJavascript() {
    canvaslist = document.getElementsByTagName("canvas");
    for(c=0; c<canvaslist.length; c++) { 
      pjs = Processing.getInstanceById(canvaslist[c]);
      try { pjs.bindJavascript(this); }
      catch(e) { setTimeout(bindJavascript, 250); }
    }
  }
  bindJavascript();
  </script>
</head>
<body>
  <canvas id="first" data-processing-sources="sketch.pde"></canvas>
  <canvas id="second" data-processing-sources="bypass.pde sketch.pde"></canvas>
</body>
</html>
Description

By default sketches loaded using Processing.js will only accept keyboard events when they have focus (i.e. after having tab-navigated to them, or having clicked on them). Using this directive will allow a sketch to receive any keyboard event sent to the page, regardless of whether the canvas it is loaded in has focus or not. Using this directive means that people who visit your page will not need to explicitly click on your sketch to interact with it, but it also means that if you have multiple sketches on a page, any sketch that uses this directive will receive input that may not have been intended for it.

Syntax
         /* @pjs globalKeyEvents="true"; */  
    
Parameters
globalKeyEvents "true" (implicitly false for any other value)
Usage Web & Application, Processing.js compatibility
Related @pjs directives

This reference is licensed under the CC BY-NC-SA 2.0 license:

Creative Commons License
Fork me on GitHub