mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
5.01k stars 393 forks source link

How to use p5 librairies? #132

Closed camilleroux closed 1 year ago

camilleroux commented 2 years ago

Hi,

Thank you very much for canvas-sketch. I'm using it a lot.

I'm using it with p5 and I'd like to use some libraries like p5.js-func. What's the best way to do that?

Thank you

linediconsine commented 2 years ago

HI, Camilleroux, in the example directory, I see a setup for p5,

Check https://github.com/mattdesl/canvas-sketch/blob/master/examples/animated-p5.js

I hope it helps

camilleroux commented 2 years ago

I saw that, but in the exemple they don't use external p5 libraries like p5.func...

mattdesl commented 2 years ago

Here's how you can hook into events like mouse, keyboard, etc:

const canvasSketch = require("canvas-sketch");
const p5 = require("p5");

const preload = (p5) => {
  // You can use p5.loadImage() here, etc...
};

const settings = {
  // Pass the p5 instance, and preload function if necessary
  p5: { p5, preload },
  // Turn on a render loop
  animate: true,
};

canvasSketch(({ p5 }) => {
  let anim = 0.5;

  // Here is how to attach interactivity to a sketch
  p5.mouseMoved = () => {
    anim = p5.mouseX / p5.width;
  };

  // Return a renderer, which is like p5.js 'draw' function
  return ({ p5, time, width, height }) => {
    // Draw with p5.js things
    p5.background(0);
    p5.fill(255);
    p5.noStroke();

    p5.rect(0, 0, width * anim, height);
  };
}, settings);
andresclua commented 4 months ago

what about p5.sound ? could you help me on this? @mattdesl

const canvasSketch = require("canvas-sketch");
const p5 = require("p5");

var sound;
const preload = (p5) => {
  // You can use p5.loadImage() here, etc...
  sound = p5.loadSound("./src/2024/sound/2024/sound.mp3");
};

const settings = {
  // Pass the p5 instance, and preload function if necessary
  p5: { p5, preload },
  // Turn on a render loop
  animate: true,
};

canvasSketch(({ p5 }) => {
  let anim = 0.5;

  // Here is how to attach interactivity to a sketch
  p5.mouseMoved = () => {
    anim = p5.mouseX / p5.width;
  };

  // Return a renderer, which is like p5.js 'draw' function
  return ({ p5, time, width, height }) => {
    // Draw with p5.js things
    p5.background(0);
    p5.fill(255);
    p5.noStroke();

    p5.rect(0, 0, width * anim, height);
  };
}, settings);