mattdesl / canvas-sketch

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

p5 mousePressed functions #118

Closed kujohn closed 2 years ago

kujohn commented 3 years ago

Is there an easy way to define mousePressed or other type of declarative functions for p5 to take in?

The roundabout way is to add event listener to the canvas for mouse clicks. Ideas?

mattdesl commented 2 years ago

Hey there, you should be able to use all the regular events (mouse, keyboard, etc) like so:

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);