Example: Using P5.js to Create a Sketch in an Angular Application
This example will show you how I built and displayed a P5.js sketch inside an Angular application. The application I built uses the standard Angular Route Provider to handle routing and one of the pages displays my P5.js sketch with the help of its controller.
Here’s an example of the sketch running on my site. The sketch itself is something I created using Processing last year before deciding I’d rather use P5 and switching over.
The Sketch and Angular
Here are the pertinent files in gist form:[https://gist.github.com/SIRHAMY/146f9069ccbe951efb1d]
Some things to notice:
- phantsaver.html is a partial that is loaded into the ng-view found in index.html
- The only time the PhantsaverCtrl (phantsaver.js) and phantsaver.html are linked is in the app.js routeProvider configuration. When phantsaver.html is loaded for the first time, PhantsaverCtrl starts running. In fact, every time you hit that route, PhantsaverCtrl will start running. - Because of this, on line 34 of phantsaver.js I check the URL of the current page. If it doesn’t have ‘phantsaver’ in it, I stop the looping and remove the canvas from the document. If I didn’t do this, the animation would continue to loop even after changing routes and the next time you came back to phantsaver, there would be two animations present.
- I’m running P5.js in instance mode. You can see the instantiation on line 94 of phantsaver.js. - I tried using P5 normally, but I was getting some weird errors when it wasn’t an instance. I can’t remember exactly what they were, but I didn’t bother with it after I got it working as an instance. I have a feeling it had to do with continuously looping through the draw function.
- The contents of phantsaver.html are positioned over the sketch elements. I don’t know if this is normal behavior or not, but it ended up turning out pretty well.
P5.js looks like a great library with simple functions that allow you to completely alter your site/app. However, there isn’t that much community support from what I’ve seen. There are posts that explain some of the more technical things of the library, but there aren’t as many examples that actually show you how things have been done in the past. This is my attempt (probably one of many) to fill that void.
That being said, I would bet that this is not an optimal configuration for P5.js with Angular. But, as I said, there wasn’t much to go off of, so my main goal was simply to get it working – and I at least accomplished that.
I hope this was helpful. Let me know if you’ve created anything cool with P5.js and/or if you’ve found a better way to get your sketches online.