What is the best way to export a variable from a p5.js file and then import it into THREE.js?

I am working on a project that involves creating a perlin noise Canva using p5.js and then importing it as a texture into a THREE.js file. However, I am encountering an error where the exported variable is not defined.

In my p5.js script, I tried using "export { variable };" which resulted in an error saying that export is not defined. In the second file with THREE.js, I used "import { variable } from './filename.js';" but it also returns an error stating that the variable is not defined.

Here is the code snippet from the first file (utilizing p5.js):

function setup() { 
  createCanvas(800, 400);
    noStroke();

    for (var x = 0; x < width; x+=1) {
        for (var y = 0; y < height; y+=1) {
            var c = 255 * noise(0.01 * x, 0.01 * y);
            fill(c);
            rect(x, y, 10, 10);
        }   
    }
}

var map = get();

if (map==null) {
    console.log("no export");
}

//export { map };

And here is the snippet from the second file (using THREE.js):

import { map } from 'http://[...].org/js/perlin.js';

Answer №1

There are several key issues that need to be addressed:

  1. p5.js in global mode is not compatible with ES modules
  2. The structure of your code causes the p5.js get() function to be called before setup() is executed.
  3. 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:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

Angularjs ng-class directive: remove a class when a different condition becomes true

The question may not be crystal clear, but I am struggling to come up with a better way to phrase it. My goal is to emphasize a table row using ng-class and conditions. Here's the snippet of code I'm currently working with: <tr ng-class="{sel ...

Leveraging UInt8Array information within a WebGL fragment shader

An HTML FFT audio analyzer is set up to output data into a UInt32Array(64) type. The three.js documentation states that this data type is not supported: https://github.com/mrdoob/three.js/wiki/Uniforms-types How can I efficiently pass my per frame FFT bu ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Implementing Highcharts in AngularJS with dynamic variables directly in the code (leveraging Pablojim's Highchart-ng library)

Currently, I am utilizing the Highchart charting library in conjunction with AngularJS by employing Pablojim's 'Highchart-ng' module. The setup is correct, and the following code functions as expected: <highchart config="{ type : ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses. <ul> <li>FIRST_STATUS</li> <li>SECOND_STATUS</li> <li>THIRD_STATUS</li> </ul> To continuously update the statuses in my contr ...

Tips for triggering an animation with button tap in Picker UI within Spark AR

After successfully following the Picker UI Patch tutorial to add buttons on my screen, I now want to incorporate animations into these buttons. Unsure of which Patches to include in my project, I have the animations listed in the Assets section for refer ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

A comprehensive guide to effectively formatting Recharts in React: addressing alignment and size management!

While attempting to style two graphs as floating cards, I am encountering difficulties in controlling the sizing and centering of the graphs. Specifically, I am having trouble with the pie chart in this example. To address this issue, I am passing paramete ...

Late data is being received in the Redux state of my React application

I am currently retrieving data from two APIs to fetch song lyrics and artist biographies. I need to store this data in my reducer, but I am facing an issue. When I make the second API call to get the biography, the data gets saved in my store successfully, ...

A method for changing the background of a textbox based on a specific condition

I have an input text field below. <label>User Type</label> <input name="user_type" id="user_type" class="form-control" readonly/> I am trying to change the background color of this textbox based on the text ...

Do STL files imported into tree.js contain vertices?

I've been experimenting with importing STL files and trying to reduce the number of vertices using a mesh simplification function I found here: https://github.com/mrdoob/three.js/issues/5806 When I import via STLLoader, it seems that geometry.vertic ...

Adding dropdown values to text area

I'm encountering a simple issue. My goal is to allow users to select values from a dropdown menu and have those values added to a text area. Additionally, users should be able to input extra content in the text area. Here's what I want: the user ...

Is there a way to restrict access to my website to only be opened in the Chrome browser?

Is there a way to prevent my web application from loading when the link is opened in browsers other than Chrome? Can this be achieved using Javascript or Java? I want to restrict the usage of my web application to only Chrome. Any assistance would be appre ...

Calling Number() on a string will result in returning a value of NaN

Currently, I am working on the following code snippet: app.put("/transaction/:value/:id1/:id2", async(req,res) => { try { const {value,id1,id2} = req.params; const bal1 = await pool.query("Select balance from balance where id=$1",[i ...

Tips for setting elevation breakpoints for Paper components in MUI

I'm currently utilizing the MUI5 framework for my Project and I must say it's been great so far. I recently created a login page where I incorporated the Paper Component. Within the Paper Component, I wanted to specify an Elevation level. This i ...

Tips for modifying the settings of a current google chart within a wrapper

Is there a way to update the options of an existing Google chart? For instance, if I want to apply these options to a chart with just a click of a button: var newOptions = { width: 400, height: 240, title: 'Preferred Pizza Toppings', col ...