How do I know when a processingjs sketch is loaded?

I wrote my own sketch during processing and pasted it into the page using processingjs and ajax, for example:

$.getScript("js/libs/processingjs.js", function() {
    $('#sketch').each(function() {
        Processing.loadSketchFromSources(this, [$(this).data('processing-sources')]);

    });
});

here is the canvas #sketchin mind:

<canvas data-processing-sources="first-sketch.pde" id='sketch'></canvas>

This works, however I also want to interact with the sketch using Javascript. When I type this in my (firebug) console, everything works fine:

var sketch = Processing.getInstanceById('sketch');
sketch.addTweet(30, 30, 100);

(addTweet is a sketch function that is available after loading a sketch) But when I put it in javascript like this:

$.getScript("js/libs/processingjs.js", function() {
    $('#sketch').each(function() {
        Processing.loadSketchFromSources(this, [$(this).data('processing-sources')]);


        var sketch = Processing.getInstanceById('sketch');
        sketch.addTweet(30, 30, 100);

    });
});

I get an error message:

Uncaught TypeError: Cannot call method 'addTweet' of undefined

I think the sketch was not loaded at the moment, is there a callback or the correct way to run the code after loading it?

I get the same error when including the processingjs library in the tag script. and run the jQuery.ready code.

+3
2

. , ().

var timer = 0,
    timeout = 3000,
    mem = setInterval(function () {
        var sketch = Processing.getInstanceById("processingCanvas");
        if (sketch) {
            console.log("SKETCH HAS LOADED");
            clearInterval(mem);
        } else {
            timer += 10;
            if (timer > timeout) {
                console.log("FAILED TO LOAD SKETCH");
                clearInterval(mem);
            }
        }
    }, 10);
+1

, loadSketchFromSources .

(github, ) loadSketchFromSources. , :

$.getScript("js/libs/processingjs.js", function() {
    $('#sketch').each(function() {
        Processing.loadSketchFromSources(this, [$(this).data('processing-sources')], function(sketch) {
          sketch.addTweet(30, 30, 100);
        });
    });
});

id. , getInstanceById.

0

All Articles