JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Processing.js keyboard input test</h1>
<p>Type some letters and they should show up below.</p>
<script type="text/processing">
PFont font;
String lastTyped;
interface JavaScript {
void startGettingUserInput();
}
void bindJavascript(JavaScript js) {
javascript = js;
lastTyped = "we have javascript!";
redraw();
}
JavaScript javascript;
void setup() {
size(400, 400);
background(0);
smooth();
noStroke();
font = createFont("Arial", 36);
textFont(font);
textAlign(CENTER);
lastTyped = "no javascript.";
}
void draw() {
background(0);
text(lastTyped, width/2, height/2);
}
void startGettingUserInput() {
if(javascript != null) {
javascript.getUserInput();
}
}
void userTypedLetterJS(String letter) {
lastTyped = letter + " (from javascript)";
redraw();
}
void mouseClicked() {
startGettingUserInput();
}
</script>
<canvas id="sketch"></canvas>
CSS
h1 {
font-weight: bold;
font-size: 120%;
}
p {
padding: 0px;
margin: 0px;
}
p+p {
margin-top: 1em;
}
.invisible_input {
color: transparent;
background-color: transparent;
border: none;
}
.invisible_input:focus {
outline: none;
}
JavaScript
var mysketch;
function getUserInput() {
var e = document.createElement("input");
e.type = "text";
e.setAttribute("class","invisible_input");
e.onkeyup = (function(p5){
return function(e) {
var event = e || window.event;
mysketch.userTypedLetterJS(String.fromCharCode(event.keyCode));
document.body.removeChild(e);
};
}(sketch));
document.body.appendChild(e);
e.focus();
}
function bindSketch() {
var pjs = Processing.getInstanceById('sketch');
if(pjs && pjs.bindJavascript) {
mysketch = pjs;
mysketch.bindJavascript(this);
} else {
setTimeout(bindSketch, 250);
}
}
document.addEventListener("DOMContentLoaded",function(){bindSketch();},false);