1

I have a webpage running 2 processing sketches, i want to call Processing.instances[0].exit() as suggested in this question: Dynamically "unload" a Processing JS sketch from canvas

But when i call Processing.instances it returns null, and i get no errors on the javascript console - also Processing.instances.length returns (0).

Here the javascript code:

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);
}
};

And here the url for the website: http://culturadigital.cc/nuevaweb

Thanks

Community
  • 1
  • 1
fartagaintuxedo
  • 749
  • 10
  • 28

2 Answers2

1

As you figured out from the pjs forum, Processing.instances is in uncertain fate. How about this:

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
      }
    }
  }
};

For reference, there might be better ways to clear the canvas here: How to clear the canvas for redrawing

Community
  • 1
  • 1
Petros Koutsolampros
  • 2,790
  • 1
  • 14
  • 20
1

If anyone else finds this question: don't use Processing.instances - we never wrote it to be accessible. There is a Processing.getInstanceById() function that you pass in your canvas id, and get back the sketch that's running on it.

Get your instance with .getInstanceById(), then call .exit() on that.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153