There are several key issues that need to be addressed:
- p5.js in global mode is not compatible with ES modules
- The structure of your code causes the p5.js get() function to be called before setup() is executed.
- The reason for commenting out the export statement is unclear.
ES Modules & p5.js
When working with an ES module, none of the top-level declarations in the module are globally accessible (such as being properties of the window
object in a web browser). p5.js functions rely on finding a global setup
function and calling it before other supported global functions like draw
. If your setup
function is within a module, p5.js will not call it unless explicitly assigned to window.setup
. To execute p5.js drawing commands when loading your module, consider using Instance mode.
Creating an ES Module Exporting p5.Graphics
Your p5.Graphics creation module should follow this structure:
// Require a p5 instance to use createGraphics without needing
// a default display canvas
let p5Inst = new p5(p => {
p.setup = () => { p.noCanvas(); };
});
export const example = p5Inst.createGraphics(200, 200);
example.fill('blue');
example.circle(100, 100, 100);
This setup allows other modules to import example
and utilize it as needed.
Implementing a p5.Graphics
Object in a THREE.js Application
Once you've successfully exported your p5.Graphics
object, the next step involves integrating it into your THREE.js app correctly. Remember that p5.Graphics
serves as a wrapper for the native Canvas
element in p5.js. Utilize the elt
property of the p5.Graphics
instance to integrate it within the THREE.js environment. Below is a basic three.js scene utilizing the p5.Graphics canvas as a texture:
import * as THREE from '/lib/three.module.js';
import { example } from '/graphics.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const texture = new THREE.CanvasTexture(example.elt);
const material = new THREE.MeshBasicMaterial({ map: texture });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
For a complete working example hosted on Replit, visit: