Processing.instances返回null

时间:2013-08-29 18:21:59

标签: javascript processing

我有一个运行2个处理草图的网页,我想按照此问题中的建议调用Processing.instances [0] .exit():Dynamically "unload" a Processing JS sketch from canvas

但是当我调用Processing.instances时它返回null,我在javascript控制台上没有错误 - Processing.instances.length也返回(0)。

这里是javascript代码:

document.onkeydown = function(e) { // or document.onkeypress
e = e || window.event;
if (e.keyCode == 115 || e.keyCode == 83) { //press "s" or "S"
    alert(Processing.instances.length);
}
};

这里是网站的网址:http://culturadigital.cc/nuevaweb

由于

2 个答案:

答案 0 :(得分:1)

正如你从pjs论坛中发现的那样,Processing.instances处于不确定的命运之中。怎么样:

document.onkeydown = function(e) { // or document.onkeypress
  e = e || window.event;
  if (e.keyCode == 115 || e.keyCode == 83) { //press "s" or "S"
    var canvases = document.getElementsByClassName("processingsketch");
            window.alert(canvases.length);
    if (canvases) {
      var ps = Array();
      for (j=0;j<canvases.length;j++) {
        ps[j]=Processing.getInstanceById(canvases[j].getAttribute('id'));
      }
      for (j=0;j<canvases.length;j++) {
        window.alert("ps " + ps[j]);
        window.alert(canvases[j].getAttribute('id'));
        if(ps[j]){ps[j].exit();} //per fartagaintuxedo's comment below: to avoid second error because once it exits then there is no longer an instance in that canvas
        canvases[j].width = canvases[j].width; //to obliterate the canvas instead of just freezing it
      }
    }
  }
};

作为参考,可能有更好的方法来清除画布:How to clear the canvas for redrawing

答案 1 :(得分:1)

如果有其他人发现这个问题:不要使用Processing.instances - 我们从未将其编写为可访问。您在画布ID中传递了一个Processing.getInstanceById()函数,并返回在其上运行的草图。

使用.getInstanceById()获取您的实例,然后在其上调用.exit()