Comments (5)
I refactored your sketch.js
file:
import * as ml5 from "ml5";
export default function sketch(p5) {
let video = null;
let setLabel = null;
let label = "test";
function modelReady() {
// Unchanged
}
function gotResults(error, results) {
if (error) {
console.error(error);
} else {
label = results[0].label;
setLabel(label); // added here
mobilenet.predict(gotResults);
}
}
p5.setup = () => {
// Unchanged
};
p5.myCustomRedrawAccordingToNewPropsHandler = function (props) {
setLabel = props.setLabel; // set the handler hook to the variable value by reference
};
p5.draw = () => {
// Unchanged
};
}
- Since in your sandbox mobilenet is already global, we don't need a variable for it.
- Since the sketch isn't a react component we don't need to import react.
- Since JS can use pass by reference for functions, we can just assign the prop to a variable and use it in our sketch anywhere we like.
Does this solve your issue?
from react.
The way I did it is generally better since the way you're doing it will re-create the gotResults
function each time the component is re-rendered which is very inneficient. Each function should be seperately declared in each case.
I did some more thoughtful refactoring in your sketch.js
file of how I might approach things:
import * as ml5 from "ml5";
let label = "";
let mobilenet = null;
let setLabel = null;
let video = null;
const predict = callback => mobilenet.predict(callback);
function gotResults(error, results) {
if (error) {
console.error(error);
return;
}
label = results[0].label;
setLabel(label);
predict(gotResults);
}
export default p5 => {
p5.setup = () => {
p5.createCanvas(400, 400);
video = p5.createCapture(p5.VIDEO);
video.hide();
p5.background(0);
mobilenet = ml5.imageClassifier("MobileNet", video, predict.bind(null, gotResults));
};
p5.myCustomRedrawAccordingToNewPropsHandler = props => {
setLabel = props.setLabel;
}
p5.draw = () => {
p5.background(0);
p5.image(video, 0, 0);
p5.fill(255);
p5.textSize(32);
p5.text(label, 10, p5.height - 20);
};
}
Of course this code isn't perfect but it is clean and ready for you to expand upon. As an example you could add some type checks for peace of mind that things won't go wrong when the code is run. As a demonstration of that, we could change the predict
function to look like so:
const predict = callback => {
if(callback instanceof Function === false) {
throw new Error("Argument 1 must be of type Function.");
}
mobilenet.predict(callback);
}
This is great because now we ensure our code is testable! Using Jest for example, we can test the predict function like so:
import { predict } from './sketch.js';
describe("predict", () => {
it("Throws with an invalid callback", () => {
expect(() => predict(null)).toThrow();
expect(() => predict("")).toThrow();
expect(() => predict(1)).toThrow();
});
it("predicts as expected", () => {
const callback = (error, results) => results[0].label;
const prediction = predict(callback);
expect(prediction).toBe("something");
})
});
Naturally more needs configured for the tests to run but this is just an idea to show you the things you could do if you chose to. Hope all of this helped somehow and if any further issues come up, just let us know!
from react.
The thing that I'm building https://codesandbox.io/s/dark-wave-dgrlg (it's a machine learning cam that will detect what the camera is seeing) You can see that the label within React is not updating but it's only updating the label in the p5 sketch.
My fix: I have done something like setInterval(setLabel, 0)
in my code but that doesn't seem to be the correct pattern? Is there a better way?
from react.
Thanks @jamesrweb yes! I've figured that out (:
Solved my issue.
from react.
export default function sketch(p5) {
function modelReady() {
console.log("Model is ready!!!")
mobilenet.predict(gotResults)
}
let gotResults = (error, results) => {}
p5.setup = () => {
p5.createCanvas(400, 400)
video = p5.createCapture(p5.VIDEO)
video.hide()
p5.background(0)
mobilenet = ml5.imageClassifier("MobileNet", video, modelReady)
}
p5.myCustomRedrawAccordingToNewPropsHandler = function (props) {
gotResults = (error, results) => {
if (error) {
console.error(error)
} else {
label = results[0].label
props.setLabel(label)
mobilenet.predict(gotResults)
}
}
}
p5.draw = () => {
p5.background(0)
p5.image(video, 0, 0)
p5.fill(255)
p5.textSize(32)
p5.text(label, 10, p5.height - 20)
}
}
However, my solution involve putting function gotResults
inside of .myCustomRedrawAccordingToNewPropsHandler
Is there a preference on how to do this?
from react.
Related Issues (20)
- Duplicate canvas when running in vite dev HOT 5
- TypeError: p5.loadSound is not a function HOT 4
- P5-wrapper size HOT 5
- Stop rerender of p5 component when redux variables update HOT 3
- Latest commits not in the npm registry HOT 5
- Issue building with Vite 5 HOT 16
- npm ERR! Usage Error: This project is configured to use npm HOT 2
- windowResized() not firing HOT 4
- Error in nextjs HOT 7
- Change p5 dependency version to minimum 1.4.1 HOT 9
- Examples directory doesn't exist, link broken on README HOT 3
- Module parse failed: Identifier 'XX' has already been declared (7762:41) HOT 3
- Is this package supported in React Native? HOT 1
- How to access custom props using abstracted updateWithProps
- Custom updaters as props for use in abstracted methods
- Missing typings for `ReactP5WrapperGuard` in 5.0.0-rc.0 HOT 2
- npm package for version 4.4.1 is empty HOT 3
- It creates new canvas once state is changed HOT 4
- How can I use @P5-wrapper/react in react native HOT 1
- drawingContext is not definied HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react.