I have written my own sketch in processing and inserted it on the page using processingjs and ajax like so:
$.getScript("js/libs/processingjs.js", function() {
$('#sketch').each(function() {
Processing.loadSketchFromSources(this, [$(this).data('processing-sources')]);
});
});
here is the canvas #sketch is referring to:
<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 great:
var sketch = Processing.getInstanceById('sketch');
sketch.addTweet(30, 30, 100);
(addTweet is a function of the sketch, which is available once the sketch has been loaded)
But when I put it inside the javascript like so:
$.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 the error:
Uncaught TypeError: Cannot call method 'addTweet' of undefined
I think the sketch has not been loaded at this point, is there a callback or a proper way to run code once it has loaded?
I receive the same error when including the processingjs lib in a script tag. and running the code on jQuery.ready.
Here is something I put together for a project of mine. It’s not pretty, but it gets the job done (for now).