The cube from Three.js refuses to render after being bundled with Webpack in a Wordpress environment

I am facing an issue while trying to incorporate three.js with WordPress using webpack. The problem lies in the fact that the 3D cube is not showing up inside the canvas.

<div class="div" id="canvas"></div>

appears to be empty.

If I were to insert the app.js code within <script> tags directly into page.php using a CDN source, it works without any problems (this method does not involve bundling).

However, I wanted to bundle it just like all the other scripts.

Here is the source code:

app.js:

import "./example.js";

example.js:

import * as THREE from 'three';

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);
$("#canvas").append(renderer.domElement);

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
requestAnimationFrame(animate);

cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

renderer.render(scene, camera);
};

animate();

page.php:

<?php

get_header();
?>


<main id="home-primary" class="site-main">
<div class="div" id="canvas"></div>

</main><!-- #main -->

<?php
get_footer();

webpack.config.js:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var path = require('path');

// adjust these variables to match your project
const jsPath= './js';
const cssPath = './css';
const outputPath = 'dist';
const localDomain = 'http://localhost:8888/jakubtrz-portfolio';
const entryPoints = {
'app': jsPath + '/app.js',
'style': cssPath + '/main.scss',

};
// rest of the configuration file...

package.json:

"devDependencies": {
    // dependencies listed here
},

// scripts section and additional configurations...

  "dependencies": {
    "three": "^0.137.5"
}

No errors are being displayed on the console.

Answer №1

Your feedback suggests that the script is currently placed in the head tag, but it should be moved to the end of the body (footer).

The reason you're not seeing anything is because your script is trying to access the canvas element before it exists. By relocating your script to the bottom, you ensure that the page has finished rendering before the script runs.

If you are using WordPress, you can achieve this by:

wp_enqueue_script( 'jakubtrz-portfolio-scripts', get_template_directory_uri() . '/dist/app.js', array(), false, true );

The last parameter specifies that WordPress should place the script in the footer. By default, it is set to false, resulting in the script being added to the head tag.

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

Is it possible to verify age on a date field in vanilla JavaScript?

How can I validate the age on a date input field? If someone is 18 or older, they will be valid. Otherwise, an error message should be displayed. Can you help me with this? ...

Can a wasm file be registered in a similar way to a JavaScript file?

My JavaScript file is calling a WebAssembly (wasm) file, but it is fetching the file from the wrong location when I register the script in a specific part of the code. To address this issue, what is considered the best practice? Here's the current s ...

Display and conceal button while scrolling in both directions

Seeking assistance with solving a coding challenge. I have created a function that reveals a button (an arrow pointing from bottom to top) when scrolling down. Now, I aim to implement another feature where the button appears after scrolling over 500 pixe ...

Achieving the extraction of a particular string from an HTML element using JavaScript

<input id="WD01B3" ct="CB" lsdata="{2:'WD01B4',4:'Any',20:'\x7b\x22WDA_TYPE\x22\x3a\x22DROPDOWN_BY_KEY\x22,\x22WDA_ID\x22\x3a\x22ABCA950297D2C0C432BAB9BB ...

Can you recommend a technology similar to WebSockets that does not rely on a framework like Node.js?

I am currently developing a basic betting game and I want to enhance the user experience by updating values in real-time. The challenge is that most of my application is written in jQuery and JavaScript, with a MySQL database set up by a different develo ...

Is there a way to verify the presence of a service worker on a specific URL?

Is there a way for me to determine if external websites have a 'service-worker' or not? Here is what I think could work: Extract all the JavaScript files from the given URL Look for the string 'sw.js' (I am not entirely sure how to ...

"Encountering a KnexTimeoutError while utilizing the knex.transactionProvider() function

I am currently working on implementing Knex transactions into my project using the relevant files provided below. However, I am encountering the following error: KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you ...

Orders in WooCommerce are being mysteriously created with no information provided and stuck in a pending payment state

Are you experiencing the issue of blank orders being generated in WooCommerce with no details and a pending payment status? I am utilizing the WooCommerce plugin along with the Elavon payment gateway, and although everything seems to be set up correctly, t ...

The port is not defined in the express when running with the command "node ."

After going through the tutorial mentioned here, everything was smooth sailing until I reached the part where I had to run the server: https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript Attempting to execute the cod ...

JavaScript is unable to bring in an npm module

Having trouble importing an npm module using import fs from 'fs'; in my main.js file that is linked with index.html. The script tag connecting the JS file has the attribute type="module". However, the browser console shows the error: Un ...

Verify that the input is zero and then proceed to deactivate the submit button if it is indeed zero in AngularJS

app.controller('HelloController', function($scope) { console.log($scope.input1); console.log($scope.input2); if (($scope.op_option == 4) && ($scope.input2 == 0)) { myForm.$invalid; } }); <form id="calc" method="pos ...

Maintain the same javascript variable throughout multiple pages

I am working on a project that involves utilizing a database along with 2 drop down menus. Through the use of JavaScript, I am able to capture the value selected from the drop down menus and then pass it on to my PHP script. The PHP script retrieves releva ...

Deciphering a Base64 document from a JSON reply on the user's end: What's the process?

My project involves rendering a file on the server side, where I pass it as a "base64" string via json. I am now faced with the task of decoding and downloading this file on the client side. Below is a simplified version of the code that is relevant to my ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Activate the enter key functionality with the help of knockout and a JavaScript function

My HTML textbox has an onkeypress event that triggers the sending of a message as shown below: <input type="text" data-bind="attr:{id: 'txtDim' + $data.userID, onkeypress: $root.sendMsg('#txtDim' + $data.userID, $data)}" /> I ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

Finding out the exact number of pixels a user will scroll when using the mouse wheel in Javascript

Is there a way to calculate the number of pixels that will be moved by the vertical scroll bar when a user scrolls using the mouse wheel in JavaScript? In my situation, the user's scrolling will result in an offsetTop change between 200px to 1000px, ...

What is the method to retrieve the name of a clicked button using JavaScript?

There are 2 <div> elements containing a minimum of 81 buttons each, all having the same class. However, they have unique ids and names. I am currently experimenting with ways to display an alert message showing the name of the button that is being ...

Display new information within a div element seamlessly without refreshing the page

Just a heads-up, I'm new to HTML development... Currently working on a website using Bootstrap. There are some buttons on the left side shown in the screenshot, and my goal is to update the content on the right without having to reload the entire pag ...