No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas.

However, when I attempt to call Processing.instances, it returns null and there are no errors displayed on the JavaScript console - additionally, Processing.instances.length also returns (0).

Below is the snippet of 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);
}
};

For reference, here is the URL of the website:

Thank you

Answer №1

It seems like Processing.instances is facing an uncertain future, as discussed on the pjs forum. Here's an alternative approach:

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

If you're looking for other ways to clear the canvas, check out this resource: How to clear the canvas for redrawing

Answer №2

For those who come across this question: avoid using Processing.instances as it was not intended to be user-friendly. Instead, there is a convenient function called Processing.getInstanceById() where you can input your canvas id and retrieve the running sketch.

Retrieve your instance using .getInstanceById(), and then execute .exit() on that particular instance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

In Angular Typeahead, the model is used as an identifier and the Text represents the name in the array object

I'm currently utilizing the Angular UI Typeahead directive available at this link. Can someone provide guidance on how to assign a model as an id and display text as a name in it? I have attempted the method below but encountered issues. Any suggestio ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

Communication between Laravel and controller using AJAX for exchanging information

I have a specific AJAX function being called from a view: function gatherProductData() { var productIds = []; $('#compare-widget tbody tr').each(function(i, ele) { productIds[i] = $(ele).data('product-id'); }); ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

What are some strategies for postponing the execution of a basic function for an

Whenever I develop microservices, I often come across situations where one function contains multiple other functions. For instance: functionA(); functionB(); functionC(); return json({status: processed}); All the functions within this block are synchro ...

Is it possible to mimic a ref attribute with jest/rtl within a functional component?

I'm currently facing an issue with a functional component that includes a helper function. function Component() { imgRef = useRef(null) function helperFunction(node, ref) { if (!ref || !ref.current) return; ...do someth ...

Is it possible for jQuery UI Dialog to function similar to an iFrame?

Is there a way to set up my dialog box with a form so that when the form is submitted, only the dialog box changes instead of the browser location? ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

Using Geolocation in HTML5 and JavaScript

Currently, I am working on my debut mobile web application and have successfully integrated Google Maps into it using Geolocation JavaScript API version 3. Now, I am looking to add a button that, when clicked by the user, centers the map on my location o ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Leverage Axios in React to dynamically fetch and display real-time data

Executing an Axios get request in order to retrieve data and display it using React. export function Wareh() { const [wareh, setWareh] = useState([{}]); useEffect(() => { axios.get("http://localhost:1515/wareh").then((response) => ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as: [1, -1, -3, 9, -2, -5, 4, 8,] We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Is there a way for me to move the dot icon along the dotline?

Here is the code snippet: jsFiddle I have successfully implemented a click event to change the style of selected dots in dotline. Now, my query is : How can I enable dragging functionality for the dot icon within dotline? Your assistance on this matte ...