Using p5js with Angular 5

Could someone explain how to use p5.js in my Angular 5 project? I am pretty new to both and was unable to import and use p5js in my Angular component. I see that the type definition file exists in the p5js lib folder, but I am still getting a bunch of “not found” errors. Surely I am doing something wrong. Would appreciate your help as I am really interested in using this library for my projects.

1 Like

Hi, the typescript support has been moved into its own repository here: https://github.com/p5-types/p5.ts

It has some updates and fixes not in the last release. I’m not familiar with Typescript myself, so I can’t offer additional advice.

This might be an old topic, but I found its still relevant as there is little I found myself on the topic.

If you have found a great way in the mean time I would love to hear it.

In my ionic4-angular project I used Renderer2 to render an element ElementRef named 'el' to the DOM and then I attached my p5 instance to that element (this.el.nativeElement).

This is the code:

import { Component, OnInit, ElementRef, Renderer2} from '@angular/core';

import * as p5 from 'p5';

@Component({
  selector: 'app-p5',
  templateUrl: './p5.page.html',
  styleUrls: ['./p5.page.scss'],
})
export class P5Page implements OnInit {

  constructor(
    private el: ElementRef,
    private renderer: Renderer2
  ) {}

  ngOnInit() {

    new p5(p => {
      let x = 100;
      let y = 100;

      p.setup = () => {
        p.createCanvas(700, 410);
      };

      p.draw = () => {
        p.background(0);
        p.fill(255);
        p.rect(x, y, 50, 50);
      };
    }, this.el.nativeElement);

  }
}

Of course you need to run npm install p5 in the project and perhaps also npm install @types/p5 first.

Hope this helps

I have created an abstract class to be able to extend it and work in a simpler way, example of use:

import { P5JSInvoker } from 'src/p5-jsinvoker';

export class RandomWalkerComponent extends P5JSInvoker implements OnInit{

  constructor() {
    super()
    this.startP5JS(document.body);
  }

  setup(p:p5) {
    p.createCanvas(400, 400);
  }

  draw(p:p5) {
    p.stroke(0);
    p.circle(200, 200, 2);
  }
}

I pass you the repository https://github.com/soler1212/P5JSInvoker