tonyketcham / p5-svelte

Easily add p5 sketches to a Svelte project 🍛 🌱
https://p5-svelte.netlify.app
MIT License
176 stars 7 forks source link

Example of importing classes from external file #372

Open vfxturjo opened 4 months ago

vfxturjo commented 4 months ago

What is the proper way to import custom classes from external js/ts files, and use the object in Sketch?

example that creates problem, looks like this: (+page.svelte) ```svelte ``` and (walker.ts) ```ts import type P5 from 'p5'; // <==================== importing p5 in external file export class walker { y: number; x: number; speed: number; size: number; constructor({ x = 0, y = 0, speed = 5, size = 5 } = {}) { this.x = x; this.y = y; this.speed = speed; this.size = size; } walk() { this.x += Math.random() * this.speed - this.speed / 2; this.y += Math.random() * this.speed - this.speed / 2; } draw() { // HERE IS THE MAIN PROBLEM..... HOW TO DRAW? p5.stroke('orange'); p5.strokeWeight(this.size); p5.point(this.x, this.y); } } ``` as i cannot access the p5 functions, i cannot draw. I tried to import p5 from 'p5' in 'walker.ts' file. it makes another problem. the ```js p5.setup = async () => { p5.createCanvas(400, 400); }; ``` have no effect then. a small p5 canvas is shown in the place. It does not work properly. ---
How it is solved: (+page.svelte) ```svelte ``` and (walker.ts) ```ts import type P5 from 'p5'; // <============================ importing type for autocompletion export class walker { y: number; x: number; speed: number; size: number; constructor({ x = 0, y = 0, speed = 5, size = 5 } = {}) { this.x = x; this.y = y; this.speed = speed; this.size = size; } walk() { this.x += Math.random() * this.speed - this.speed / 2; this.y += Math.random() * this.speed - this.speed / 2; } draw(p5: P5) { // <=============================== p5 added here p5.stroke('orange'); p5.strokeWeight(this.size); p5.point(this.x, this.y); } } ``` what i don't like about this solution is to use any function that will use p5.js things, I will have to pass it when calling. I believe there should be a better way to do it. ---

I may be doing things in the wrong way, please correct me learn if that is the case, like

A clear example on how to do these in the documentation page for can be very helpful.