freshfork / p5.EasyCam

A p5.js library for easy 3D camera control.
https://freshfork.github.io/p5.EasyCam
MIT License
138 stars 33 forks source link

Support module bundling, and support dynamic p5 runtime contexts #27

Open jackwh opened 1 year ago

jackwh commented 1 year ago

Further to the discussion in #26, this PR does two things:

  1. Wrap the EasyCam code in a UMD module. EasyCam can now be imported and used in modular projects. This allows tools like Webpack or Vite to bundle code which relies on it.
  2. Allows the p5 context to be set dynamically. The code previously expected p5 to be available globally, which won't always be the case if p5 is aliased or bundled.

Example code demonstrating these changes:

import * as mySketch from "p5";
import EasyCam from "p5.easycam";

// ...

mySketch.setup = () => {
  // Tell EasyCam to use the "mySketch" context:
  EasyCam.setContext(mySketch);

  // Create a camera
  cam = mySketch.createEasyCam();
};

// ...

The traditional <script src="..." /> approach still works as before. I've checked all the examples, and everything seems to be backwards-compatible.

The only bit I'm unsure about is whether the TypeScript definitions need changing, now the code's wrapped in a module. I understand the types are a work-in-progress so perhaps someone can advise on that.

jwdunn1 commented 1 year ago

Good work here! I copied the modified p5.easycam.js file from this PR and tested a dozen or more of my EasyCam sketches on OpenProcessing and editor.p5js.org. They all worked perfectly, both global and multi-instance sketches. I'll look into the TypeScript definitions tomorrow when I find time. Were you able to import this modified version successfully into your Yarn/TypeScript project?