2

I am building a angular component clock.component with p5js.

Full source from her: https://github.com/avsmips/angular4-p5js-app/blob/master/src/app/analog-clock/analog-clock.component.ts

Html:

<div id="analog-clock-canvas"></div>

Ts:

createCanvas() {
   console.log("creating canvas");
   this.p5 = new p5(p => this.drawing(p));
}

drawing(p) {
   p.setup = () => {
   p.createCanvas(400, 400).parent("analog-clock-canvas");      
   ...
}

p5 creates a canvas and adds into parent div analog-clock-canvas with 1 declaration. However it also add the canvas into the first compoment if multiple compoments are used.

<div class="flow">
  <app-clock></app-clock>
  <app-clock></app-clock>
</div>

enter image description here

beewest
  • 4,486
  • 7
  • 36
  • 63
  • Could you expand on how exactly the `drawing` function works? What is `p`? – igg Mar 20 '20 at 10:40
  • just copy from this project: https://github.com/avsmips/angular4-p5js-app/blob/master/src/app/analog-clock/analog-clock.component.ts – beewest Mar 20 '20 at 13:21

1 Answers1

2

The problem is the parent('analog-clock-canvas') selects by id, and all components have the same, since you have hard coded it (I'm talking about <div id="analog-clock-canvas"></div>). Selecting by id, will bring the first result that matches, regardless of how many exists in the DOM.

I recommend generating a unique id in your component's ngOnInit and assigning it to the div. I like to use GUIDs. For example, using this implementation:

analog-clock.component.ts

...

private containerId: string;

...

ngOnInit() {
    this.containerId = this.uuidv4();
}

...

// Taken from:
// https://stackoverflow.com/a/2117523/12398336
private uuidv4() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

...

private drawing = function(p: any) {
    p.setup = () => {
      p.createCanvas(400, 400).parent(this.containerId);      
      ...

analog-clock.component.html

<div [id]=[containerId]></div>
igg
  • 2,172
  • 3
  • 10
  • 33