ProcessingJS 中的按键不起作用

Key Pressing in ProcessingJS Doesn't Work

我有一个 ProcessingJS 项目,我把它放在本地 HTML 页面上。这是代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<script src="https://raw.githubusercontent.com/processing-js/processing-js/v1.4.8/processing.min.js"></script>
<script type="text/processing" data-processing-target="processing-canvas">
size(400,400);
background(141,141,141);
keyPressed = function() {
        if(key+"" === "82" || key+"" === "114"){ // "r" or "R"
            text("Hi", 10,10);
        }
        return;   
};
</script>
<canvas id="processing-canvas"> </canvas>

</html>

出于某种原因,当我打开 HTML 页面时,我可以看到一切正常(因为我看到灰色背景),但是当我单击 'r' 或 'R' 按钮。这是为什么?

这看起来不正确:

if(key+"" === "82" || key+"" === "114"){

来自the Processing.js reference,应该是这样的:

if (key == 'r' || key == 'R') {

我不确定您为什么要在代码中比较 String 值,但这可能与 JavaScript not having a char datatype:

有关

JavaScript only knows about numbers, and strings, unlike Java, which also knows about "char" data types. The char is a 16 bit unsigned integer value, that can also pretend to be a letter (from the ISO8859-1 codepage for the first 256 numbers, and basically magic after that). Unfortunately, as JavaScript has no equivalent, relying on char comparisons to be either numbers or letters is quite likely to cause problems. If you have Processing code where you're comparing chars, you will either have to perform int casting, or string casting, using the int() and str() functions, so that you know you're explicitly comparing datatypes that JavaScript can deal with.

但我认为您没有正确进行转换。您可以尝试使用 int()str() 函数(同样,the reference 是您最好的朋友)。

所以我想通了!我在做的是我在写

keyPressed=fuction(){
   // CODE
};

然而,我应该写:

void keyPressed(){
    // Code
}

一个处理canvas默认要写在java里,如果你想写在java脚本里,可以加一点额外的html:

    <head>
      <script src="processing.js"></script>
    </head>
    <body>
      <canvas id="canvas1 width="400" height="400"></canvas>
      <script id="script1" type="text/javascript">
        function sketchProc(processing) {
          //Code goes here
          processing.draw = function() {
            //This is the draw function
          }
        }
        var canvas = document.getElementById("canvas1");
        // attaching the sketchProc function to the canvas
        var p = new Processing(canvas, sketchProc);
        // p.exit(); to detach it
      </script>
    </body>