1

I'm trying to incorporate the p5js javascript library into my Ember.js app. I want the following p5js example to appear on the template:

https://p5js.org/examples/sound-record-save-audio.html

I've included the cdn script in my index.html file:

I dont know how/where in the Ember run loop to put the javascript so it runs and loads when the page loads

2 Answers2

2

I would suggest making a component, putting the component in whatever template you're rendering (could be application.hbs if you only have one page) and putting the Javascript into the component's didInsertElement method.

Along with that, I would place the p5 canvas inside your component's own Element, so that the component behaves normally (it's weird for a component to render things outside its own Element, and you'd want them to be cleaned up properly if you navigate away to some other template). The p5 docs say how to position the canvas.

In your component it would look like:

export default Component.extend({
  didInsertElement() {
   createCanvas(400,400);
   canvas.parent(this.element);
   background(200);
   fill(0);
   text('Enable mic and click the mouse to begin recording', 20, 20);
   ...etc...  
  }
})

```

Ed4
  • 2,277
  • 18
  • 18
0

This answer applies for Ember app versions 1.13 onward and was written as of 3.x. Versions of Ember < 3.x will need to use the older import syntax in the component boilerplate.

The most common place for code that should run after a page loads is the didInsertElement hook:

import Component from '@ember/component';

export default Component.extend({
  didInsertElement() {
    this._super(...arguments);
    console.log(p5) // this should print a function to the console
  }
});

Also check out didRender, which might be a better fit for your use case.

You can read more about the uses of different component lifecycle hooks in The Guides

handlebears
  • 2,168
  • 8
  • 18