gherciu / react-p5 Goto Github PK
View Code? Open in Web Editor NEW๐จ This Component lets you integrate p5 Sketches into your React App.
Home Page: https://codesandbox.io/s/k09k8knxz5
License: MIT License
๐จ This Component lets you integrate p5 Sketches into your React App.
Home Page: https://codesandbox.io/s/k09k8knxz5
License: MIT License
I'm having trouble getting the windowResized function to work. I've got the following in my code (the console.log is just to try to see if its being called):
windowResized = p5 => { p5.resizeCanvas(p5.windowWidth, p5.windowHeight) console.log('resize') }
I've also tried windowResized() { ... }
thanks for any help you can give
Would it be possible to use https://github.com/zenozeng/p5.js-svg with this library so we can export the canvas as svg ?
This would be amazing.
Hi,
So this might be down to wrong usage, but I have a problem:
I want to use the p5 mouse/touch event stuff in order for my user to be able to interact with the canvas. I also have other Components on the same page. When I now register a listener for these events, it always executes, even outside of the canvas bounds. Is this an issue on your end? Or a p5 issue? Does it come down to wrong usage?
Thank you for your time
this maybe a silly question but there's another lib with an almost identical API it seems (at first) I was wondering if there are any major differences in the design or choices you made?
I am trying include a class, but gets error message "TypeError: Symbol is not a constructor"
Here is code
let symbol
export default class P5 extends Component {
setup = (p5, canvasParentRef) => {
p5.createCanvas(p5.windowWidth, p5.windowHeight).parent(canvasParentRef);
symbol = new Symbol(p5, 100, 300)
symbol.setToRandomSymbol()
};
windowResized = p5 => {
p5.resizeCanvas(p5.windowWidth, p5.windowHeight)
};
draw = p5 => {
symbol.render()
}
Symbol = (p5, x, y) => {
this.x = x
this.y = y
this.value = 0
this.render = function () {
p5.fill(0, 255, 70)
p5.text(this.value, this.x, this.y)
}
}
render() {
return <Sketch setup={this.setup} draw={this.draw} />
}
}
Can't seem to invoke the webgl mode of p5.js the usual way (adding the keyword WEBGL as a third parameter in createCanvas). Is the WEBGL mode supported?
I am getting this error when I try to use npm run build
.
It works well when I run locally , but whenever I try to build this , it shows this error "Super Expression either be null or a function. Please help
Nevermind, I forgot to import the image first, now its working, I not sure how to delete this issue ^^
I bumped into an issue with using erase() and noErase() in Typescript. The interpreter insists that these are unknown properties:
const mouseMoved = (p5: p5Types) => {
p5.erase(255, 0)
p5.ellipse(p5.mouseX, p5.mouseY, 10)
p5.noErase()
}
They definitely exist, everything works perfectly when I instruct Typescript to ignore these lines.
const mouseMoved = (p5: p5Types) => {
// @ts-ignore
p5.erase(255, 0)
p5.ellipse(p5.mouseX, p5.mouseY, 10)
// @ts-ignore
p5.noErase()
}
I am trying to use p5's webcam / video capture functional in my react application. I found an example with Sketch and it worked. However, when I try to change the given sketch to the video thing (code inspired by ml5.js documentation), it does not work because VIDEO is not defined.
let capture;
export const YourComponent: React.FC<ComponentProps> = (props: ComponentProps) => {
let x = 50;
const y = 50;
//See annotations in JS for more information
// const setup = (p5: p5Types, canvasParentRef: Element) => {
// p5.createCanvas(500, 500).parent(canvasParentRef);
// };
// const draw = (p5: p5Types) => {
// p5.background(0);
// p5.ellipse(x, y, 70, 70);
// x++;
// };
let capture: p5Types.Element;
const setup = (p5: p5Types, canvasParentRef: Element) => {
p5.createCanvas(390, 240);
capture = p5.createCapture(VIDEO);
capture.size(320, 240);
//capture.hide();
}
const draw = (p5: p5Types) => {
p5.background(255);
p5.image(capture, 0, 0, 320, 240);
p5.filter(INVERT);
}
return <Sketch setup={setup} draw={draw} />;
};
Cannot find name 'VIDEO'.
It's the same for invert.
Here's something similar but it is in plain javascript, not react.
https://github.com/ml5js/ml5-library/blob/main/examples/p5js/ImageClassification/ImageClassification_Video/sketch.js
How can I reproduce this in react?
I have a Router, and a component which implements a <Sketch />
. This is placed on the top of the Router, so it will stay there on every page. When i am pragmatically navigating between the pages, the p5 drawing stops. The canvas is still exists in the DOM, but it gets cleared. Only way to get them back is by refreshing the entire page.
Any idea how to go around this problem?
Thank you!
Hi! I noticed an issue with resolved this module in Gatsby project I'm working on using the latest version (1.3.8).
Can't resolve 'react-p5' in '/Users/bomani/Desktop/code/personal/src/pages/experiments'
Switching to 1.3.6 seemed to have resolved the issue. Here's a reference to the code in question if you'd like to take a look and try switching the version of the react-p5 to the latest one and running npm install
and gatsby develop
!
https://github.com/bomanimc/personal/tree/noc
There seems to be a 4px bottom margin in the react-p5 div surrounding the canvas. This is creating overflow when I try to make the entire window the canvas.
The sandbox code shows the height of the div at 204px.
Thanks!
I'm getting close to a solution here. My problem is that I need to use a p5 method inside my useEffect to load an image but the useEffect doesn't have access to the p5 object. I'm going to need to use the p5 object for some other useEffects as well. Is there a way to pass it to it somehow?
// 3rd party imports
import React, { useState, useEffect } from 'react';
import Sketch from 'react-p5';
import p5Types from 'p5';
// Styles
import './PreviewSketch.scss';
// Types
interface PreviewSketchProps {
height?: number;
width?: number;
imgString: string;
}
function PreviewSketch({
height = 200,
width = 200,
imgString,
}: PreviewSketchProps) {
const [mainImage, setMainImage] = useState<any>();
useEffect(() => {
p5.loadImage(imgString, (img: any) => {
setMainImage(img);
});
}, [imgString]);
function setup(p5: p5Types, canvasParentRef: Element) {
p5.createCanvas(height, width, p5.WEBGL).parent(canvasParentRef);
}
function draw(p5: p5Types) {
p5.background('#FFF');
if (mainImage) {
p5.texture(mainImage);
}
p5.rotateX(p5.frameCount * 0.01);
p5.rotateY(p5.frameCount * 0.01);
p5.fill('red');
p5.box(20);
}
return (
<div className="preview-sketch">
<Sketch setup={setup} draw={draw} />
</div>
);
}
export default PreviewSketch;
Although there is a check in place:
Line 4 in f029ba7
The build still fails for me. This could be the case, because of the one-liner if statement. It could lead to an error during static analysis, but that's speculation. Do you have more insight on what could cause this even though it should normally be prevented?
The complete error from the console:
WebpackError: ReferenceError: window is not defined
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:330179
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1439
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1475
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:272442
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1439
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1475
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:230003
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1439
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1570
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1591
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:612542
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:373
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:612637
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:373
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1176
- index.js:1
[Dolce Stil Criollo]/[react-p5]/build/index.js:1:1193
Could the code be included unminified during development and be minified only for production? Are the gains through minifing so great here, that it justifies the increased difficulty with debugging?
Otherwise it makes all errors really hard to follow, also with errors unrelated to the build.
I will create a PR for adding brackets to the one-liner as a fail-safe. I am not sure whether that will actually fix the issue, but it is worth a shot? Unfortunately I can't test this out myself as there are some build steps involved that I don't quite understand. Maybe you could clarify in the docs, how one goes about local development of this package.
I will also create a new issue asking about local development of this package.
Is anybody else building successfully using Gatsby v3?
hello! I would be super happy if anyone could share code where p5 sound library is used with react-p5 and next.js.
keep getting p5.loadSound() is not a function
I was trying to move a circle using p5.Vector.add()
but neither p5.Vector.add()
nor p5.p5.Vector.add()
exists. How do I access these properties? If I can't access them, is there some workarounds to do so?
Thanks in advance.
[email protected]
was released 5 months ago. I assume react-p5 doesn't need to change to support [email protected]
, but the peer dependency still says ^0.7.3
, currently installing [email protected]
.
I assume a change to >=^0.7.3
might fix it, but I'm no package expert, and wasn't able to test it on my machine.
I'm trying to embed a p5.js sketch using this library in a project I'm working on.
The following sketch yields the following error:
index.js:47 TypeError: Cannot read property 'remove' of undefined
at t.value (index.js:19)
import React, { Component } from "react"
import Sketch from "react-p5"
let particles_a: any[]
let particles_b: any[]
let particles_c: any[]
let nums = 200
let noiseScale = 800
export default class Processing extends Component {
x = 50
y = 50
setup = ({ p5 }: any, { canvasParentRef }: any) => {
p5.createCanvas(p5.windowWidth, p5.windowHeight).parent(canvasParentRef) // use parent to render canvas in this ref (without that p5 render this canvas outside your component)
p5.background(21, 8, 50)
for (var i = 0; i < nums; i++) {
particles_a[i] = new Particle(
p5.random(0, p5.windowWidth),
p5.random(0, p5.windowHeight),
p5
)
particles_b[i] = new Particle(
p5.random(0, p5.windowWidth),
p5.random(0, p5.windowHeight),
p5
)
particles_c[i] = new Particle(
p5.random(0, p5.windowWidth),
p5.random(0, p5.windowHeight),
p5
)
}
}
draw = ({ p5 }: any) => {
p5.noStroke()
p5.smooth()
for (var i = 0; i < nums; i++) {
var radius = p5.map(i, 0, nums, 1, 2)
var alpha = p5.map(i, 0, nums, 0, 250)
p5.fill(69, 33, 124, alpha)
particles_a[i].move(p5)
particles_a[i].display(radius, p5)
particles_a[i].checkEdge(p5)
p5.fill(7, 153, 242, alpha)
particles_b[i].move(p5)
particles_b[i].display(radius, p5)
particles_b[i].checkEdge(p5)
p5.fill(255, 255, 255, alpha)
particles_c[i].move(p5)
particles_c[i].display(radius, p5)
particles_c[i].checkEdge(p5)
}
}
render() {
return <Sketch setup={this.setup} draw={this.draw} />
}
}
class Particle {
dir: any
vel: any
pos: any
speed: any
constructor(x: number, y: number, p5: any) {
this.dir = p5.createVector(0, 0)
this.vel = p5.createVector(0, 0)
this.pos = p5.createVector(x, y)
this.speed = 0.4
}
move = (p5: any) => {
var angle =
p5.noise(this.pos.x / noiseScale, this.pos.y / noiseScale) *
p5.TWO_PI *
noiseScale
this.dir.x = p5.cos(angle)
this.dir.y = p5.sin(angle)
this.vel = this.dir.copy()
this.vel.mult(this.speed)
this.pos.add(this.vel)
}
checkEdge = (p5: any) => {
if (
this.pos.x > p5.windowWidth ||
this.pos.x < 0 ||
this.pos.y > p5.windowHeight ||
this.pos.y < 0
) {
this.pos.x = p5.random(50, p5.windowWidth)
this.pos.y = p5.random(50, p5.windowHeight)
}
}
display = (r: number, p5: any) => {
p5.ellipse(this.pos.x, this.pos.y, r, r)
}
}
Hey! I have a problem:
With the following code I get the error 'Module not found: Can't resolve 'react-p5' in 'C:....'.
I ran 'npm i p5 react-p5' and also checked the package.json. If I hover over the importet 'Sketch' it even shows the proper information on that. Everything seems to be correct but it just won't work and I couldn't find anything in the Internet.
import React, {useState,useRef} from 'react'
import Sketch from 'react-p5'
const Seperator = () => {
const sketchContainer = useRef(null)
let currentPage
const preload = p5 => {
p5.loadImage('../resources/test.png', img => {
currentPage = img
})
}
const setup = (p5, sketchContainer) => {
p5.createCanvas(500, 500, p5.WEBGL).parent(sketchContainer)
}
const draw = p5 => {
p5.image(currentPage, 0, 0)
}
return (
<div ref={sketchContainer}>
<Sketch preload={preload} setup={setup} draw={draw} />
</div>
)
}
export default Seperator
TypeError: p.textWrap is not a function
Does p.textWrap(p.CHAR) not work or is it just me?
For example i have to pages:
In the Game Page, i maked a canvas, and when i open e.g localhost/game the canvas can load.
but when i enter to game page from other routes, canvas can't be load at all.
If I use the work around to use p5.sound by importing as -
import "p5/lib/addons/p5.sound";
and I am using tone.js in another react class like -
const osc = new Oscillator("100").toDestination();
I get the following error on page load -
Is this something I shouldn't be doing i.e. you can only use one sound library at a time or is there a way round this? If I remove the p5.sound import the error goes away...
Hi, this is probably a rookie issue but I am having some issues accessing the p5 sound library via react-p5. I got the simple sketch working via vanilla HTML and JS and I am now trying to get it working with React. I see that the code for p5.sound.js in the the addons of the node module, however, I can't seem to make use of it.
The error I am receiving is that p5.loudSound is not a function. Any help at all would be greatly appreciated!
Here is the code:
import React, { Component } from 'react';
import Sketch from "react-p5";
import "react-p5/node_modules/p5/lib/p5";
import 'react-p5/node_modules/p5/lib/addons/p5.sound';
import './App.css';
export default class App extends Component {
song;
amp;
loadedState = false;
setup = p5 => {
p5.createCanvas(p5.windowWidth, p5.windowHeight);
p5.angleMode(p5.DEGREES);
this.song = p5.loudSound("song.mp3", this.loaded);
this.amp = new p5.Amplitude();
}
loaded() {
this.loadedState = true;
}
keyPressed() {
if(this.loadedState)
this.togglePlaying();
}
togglePlaying() {
if (!this.song.isPlaying()) {
this.song.play();
} else {
this.song.pause();
}
}
volHistory = [];
draw = p5 => {
p5.background(0);
let vol = this.amp.getLevel();
this.volHistory.push(vol);
p5.stroke(255);
p5.noFill();
p5.translate(p5.width/2, p5.height/2);
p5.beginShape();
for(let i = 0; i < 360; i++) {
let r = p5.map(this.volHistory[i], 0, 1, 50, 500);
let x = r * p5.cos(i);
let y = r * p5.sin(i);
p5.vertex(x, y);
}
p5.endShape();
if(this.volHistory.length > 360) {
this.volHistory.splice(0, 1);
}
}
render() {
return <Sketch setup={this.setup} draw={this.draw}/>
}
}
Hey I'm using this Component in a Next.js project to animate a low-poly landscape.
When invoking useState
(see _app.js
), the canvas suddenly stops drawing or at least it seems to no longer be visible.
The canvas is still in the DOM, resizing the window seems to fix this. Something similar happens when something is changed in the next.js project and hot-reload is kicking in, so these might be related to one another.
https://codesandbox.io/s/interesting-rgb-r09mf?file=/components/animatedTerrain.js
On my empty nodejs project I ran
npm install --save react-p5
There is no build folder, I needed then to checkout this project from git, build it and copy the build folder across to my node_modules/react-p5/
folder.
This is an error about loadImage()
.
I'm currently running a p5js program in the following environment.
When I try to load the test.jpg
in assets
folder, I get the following error.
test.jpg:1 GET http://localhost:3000/assets/test.jpg 404 (Not Found)
p5.js says: It looks like there was a problem loading your image. Try checking if the file path [http://localhost:3000/assets/test.jpg] is correct, hosting the image online, or running a local server.[https://github.com/processing/p5.js/wiki/Local-server]
How do I get the images on the server to load?
Thank you.
I am not able to use DOM elements in react.
var button = p5.createButton('click me') button.position(this.x, this.y)
it is not showing on the screen.
I tried to get the AudioIn working, but couldn't figure it out. I'm trying to record audio. How would I call the new AudioIn(). Thanks!
Hi,
I'd like to render a p5 canvas inside of a react component.
Is there a convenient way to make the canvas fit the component dimensions?
My original idea was to fetch the parent component's dimensions using the useRef hook and pass them to a child that contains the p5 canvas.
But this way I alway had the problem that scroll bars were introduced and I wasn't able to hide them.
thanks in advance :)
Hey @Gherciu !
Thank again for your work!
I wanted to create this issue specifically for getting to know more about how to develop react-p5
locally.
Forking it, then including the fork as a dependency in package.json doesn't seem to work as there are some built steps missing that go along with npm publish
?
So far the docs only include information on how to contribute to the project, but not how to do successful local development.
This could be awesome additional information for the docs as it would allow many more people to contribute.
(if you prefer to move this issue to the discussion
feature of Github, please feel free to do so)
How can I use p5.dom methods like createVideo with react-p5?
how would i use this as a functional component rather than a class based one. Not essential, but I'm doing everything else that way and ran into a few errors when i tried to convert it
I am trying to call the function createVector
outside the setup
and draw
functions. I have tried window.p5.createVector
, createVector
and p5.createVector
, but all of them cause is not a function
error. So how should I instead call createVector
?
when i run npm install react-p5, it's getting errors relating to new version reactjs "Could not resolve dependency peer react@"^16.2.0" from [email protected]"
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.2.0" from [email protected]
npm ERR! node_modules/react-p5
npm ERR! react-p5@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Do\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Do\AppData\Local\npm-cache\_logs\2021-02-10T16_05_35_458Z-debug.log
PS D:\Side\fastest-hand-in-the-west> npm i p5
Terminate batch job (Y/N)?
^C
PS D:\Side\fastest-hand-in-the-west> npm i p5
added 1 package, and audited 1964 packages in 5s
125 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
PS D:\Side\fastest-hand-in-the-west> npm i react-p5
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.2.0" from [email protected]
npm ERR! node_modules/react-p5
npm ERR! react-p5@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Do\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Do\AppData\Local\npm-cache\_logs\2021-02-10T16_07_08_889Z-debug.log
PS D:\Side\fastest-hand-in-the-west> npm i --save react-p5
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.2.0" from [email protected]
npm ERR! node_modules/react-p5
npm ERR! react-p5@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Do\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Do\AppData\Local\npm-cache\_logs\2021-02-10T16_08_57_364Z-debug.log
PS D:\Side\fastest-hand-in-the-west> npm i --save react-p5@latest
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.2.0" from [email protected]
npm ERR! node_modules/react-p5
npm ERR! react-p5@"1.3.8" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Do\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Do\AppData\Local\npm-cache\_logs\2021-02-10T16_09_10_516Z-debug.log
How can I access Vector functions using dynamic import in next.js? Would be thankful if anyone had a solution.
I can't find a way of using the windowWidth property and was wondering if something is different here.
ex: /lib /src ..rest
I have this:
import p5Types from "p5"; //Import this for typechecking and intellisense
but that doesn't define the global types
if i pass around an instance of that I can use it:
initDrawing(p5: p5Types) {
p5.blendMode(p5.BLEND)
...
but that is a bit of hassle.
do you define the global types in a more accessible way?
Hi, thank you for your work on this package. I wondered if there is a way of implementing p5's windowResized
function. I'm trying something like the below:
export default (props) => {
colorTeal;
console.log('๐ ~ file: index.js ~ line 10 ~ colorTeal', colorTeal);
const x = props.x;
const y = props.y;
const setup = (p5, canvasParentRef) => {
p5.createCanvas(window.innerWidth, window.innerHeight).parent(
canvasParentRef
);
};
const draw = (p5) => {
p5.background('#319795');
p5.ellipse(x, y, 70, 70);
x++;
};
const windowResized = () => {
resizeCanvas(window.innerWidth / 2, window.innerHeight / 2);
};
// Will only render on client-side
return <Sketch setup={setup} draw={draw} windowResized={windowResized} />;
};
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.