A WordPress website featuring the impressive capabilities of the Three.js JavaScript 3D library

I attempted to integrate the Three.js JavaScript 3D library into my WordPress website by including three.min.js in various parts:

  1. Within the body of a post

    
    <script src="/three.min.js"></script>
    

  2. In the footer

    
    <script type='text/javascript' src='/three.min.js'></script>
    

  3. And in the Pinboard: Theme Functions (functions.php) file

    
    function pinboard_enqueue_scripts() {
    wp_register_script('three.min', '/three.min.js', true);
    wp_enqueue_script( 'three.min' );
    }
    add_action( 'wp_enqueue_scripts', 'pinboard_enqueue_scripts' );
    

Regrettably, the cube from Mr.doob’s page is not displaying on my Cube page.

I would greatly appreciate any assistance with getting Three.js to function correctly on my WordPress site.

Thank you.

Answer №1

When it comes to CSS, there's a lot you can do ^^ I personally follow a similar approach on my website . If you need some inspiration, feel free to check it out. In the wordpress theme editor, I made changes to the header file (header.php) to include both the library and script there. I used an absolute URL (yes, I took a shortcut, but you might find a better way with more patience) and added the libraries and script like this:

</head>
<body <?php body_class(); ?>>
    <!-- The additions start here (after head & body in Heaper.php) -->
    <div id="3dcontainer" style="position: fixed; z-index: -1;"></div>
    <div id="page" class="hfeed site">
    <header id="masthead" class="site-header" role="banner" style="overflow: visible;">

    <script src="http://lizkats.com/wp-content/fromGame/three.js"></script>
    <script src="http://lizkats.com/wp-content/fromGame/models/modelMeerkatPoseWeb.js"></script>
<script>

        var container, stats;

        var camera, scene, renderer, objects;

        var clock = new THREE.Clock();


        function init() {

            container = document.getElementById('3dcontainer');

            camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.5, 200 );
            camera.position.set( 0.4, 0.42, 0.9 );

            scene = new THREE.Scene();

            // ...

            // Renderer

            renderer = new THREE.WebGLRenderer( { alpha: true } );
            renderer.setClearColor( 0x453326, 1);
            renderer.setSize( window.innerWidth, window.innerHeight);

            container.appendChild( renderer.domElement );

            animate();
        }

        init();

        function animate() {

            requestAnimationFrame( animate );


            render();
        }

        function render() {

            var delta = clock.getDelta();

            renderer.render( scene, camera );
        }
</script>

The 3dcontainer is where I place the canvas object.

Additionally, don't forget to update your style.css to get the desired look. Here's a link to my current stylesheet for reference: http://pastebin.com/9uUiAZhY

Best of luck!

Answer №2

If you're searching for ways to integrate a three.js cube into your Wordpress site, you've come to the right place. Below is a simple guide to help you achieve this without using bundlers like npm:

1. Open your index.php or page.php file based on your Wordpress configuration.

2. Start by importing the three.js library either via CDN or npm:

CDN Method:

<script type="module">
// Locate the latest version at https://cdn.skypack.dev/three.
import * as THREE from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9febf7edfafadfafb1aeaca8b1aa">[email protected]</a>';

const scene = new THREE.Scene();
</script>

If you choose the npm method, run npm install three in your terminal to create the necessary node_modules folder containing the library. Remember that for this tutorial, we won't be bundling the HTML as recommended in the official three.js docs. Enqueue the library in your functions.php file:

wp_enqueue_script( 'three-min', get_template_directory_uri() . '/node_modules/three/build/three.min.js', array(), null, false );

Note that this script should be placed in the <head> section to ensure it runs before any other scripts.

3. Now, let's add a basic cube to your script:

<script type="module">

// Locate the latest version at https://cdn.skypack.dev/three.

import * as THREE from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5f43594e4e6b1b051a181c051e">[email protected]</a>';

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();
            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();


</script>

If using NPM, omit

import * as THREE from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffbe7fdeaeacfbfa1bebcb8a1ba">[email protected]</a>';
as it's not required due to the UMD import. Keep an eye out for future updates regarding Webpack bundler integration!

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

Retrieving information from a MYSQL database table and populating a text field with AJAX and PHP

Is there a way to use AJAX to display the data from an array that is called in getword.php into a text field in index.php? Let's take a look at the code below: Here is the code snippet from index.php: <body> <div class="container" ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

Tips for consolidating JavaScript assets in Mean.io

Recently, I started using Mean.io and encountered an issue while trying to include an external .js file in my package. Unfortunately, I seem to be doing it incorrectly as the file is not being added to aggregated.js. This is the approach I have taken: im ...

Ways to continuously monitor an array until specific criteria are fulfilled

My goal is to search for a specific item in an array called idarray and loop through it until I find a value that is not equal to -1. Once I find that value, I want to use the index to retrieve the corresponding value from another array called array. To a ...

What is the formula for determining the REAL innerWidth and innerHeight?

I am currently working on a responsive website using Bootstrap and I am looking to create an element that perfectly fits the screen size. When I set the height/width to 100%, the browser includes the toolbar, other tabs, and the Windows taskbar in the cal ...

Extract the property value and save it as an array in Vue

Looking to extract all values of a specific property and save them as an array. I attempted the following method: data() { return { roomList: null } }, methods: { getRooms() { var that = this axios.get('http://local ...

Tips for managing content and tables that exceed their container's boundaries

On my webpage, I have a slide-out sidebar that shifts the other contents and causes overflow with a scrollbar. I want the content to remain inside the window and adjust according to the available space. Image of Slide-out Sidebar As seen in the image, t ...

Master the art of sending multiple asynchronous requests simultaneously with suspense in Vue 3

Utilizing <Suspense>, I am handling multiple requests in my child component using the await keyword: await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res); await store.dispatch("product/get ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...

Issue with top-level navigation menu dropdown functionality

I am experiencing an issue with a dropdown menu that has top level and two sub levels. The problem is that while the sub levels function correctly when clicked, the top level does not navigate to the intended page upon clicking. var menu_Sub = $(".men ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

AngularJS property sorting: organize your list by name

I have a complicated structure that resembles: { 'street35':[ {'address154': 'name14'}, {'address244': 'name2'} ], 'street2':[ {'address15& ...

Expand the Canvas element to match the size of the div below

I am working with a canvas that I want to span 100% of the screen width and at least 100% of the screen height, with the ability to extend further if the next div exceeds the bottom of the screen. To populate the canvas, I am using Trianglify. `` ...

Navigating with NextJS to a personalized URL and managing the feedback from an external application

I'm currently in the process of developing an application that involves redirecting users to a specific URL, prompting them to open an app (with a url starting with zel:), and then sending a request back to my server. Here's the envisioned user j ...

Display the user's username on the navigation bar once they have successfully

I am having trouble displaying the username after logging in on the navbar. After logging in with the correct credentials, I am redirected to the page, but the navbar doesn't update with the username. Can someone provide some tips on what I should do ...

Refreshing image does not reload

function updateimage(){ $("#fileimg").attr("src","path/to/image.jpg"); $('#fileimg').fadeIn('slow'); setTimeout(updateimage, 5000); } Greetings, I am trying to refresh an image every 5 seconds but it's not working as ...

Accessing a file located in a specific directory using the node fs module

Currently, I am attempting to access a file from my local system using the 'fs' module in node.js. However, I have encountered an issue where the 'fs' module does not seem to function properly when an absolute path is provided. Here is ...

Prevent the print dialog window from appearing when a page loads in Selenium for Firefox and Chrome

Is there a way to prevent the print window from automatically popping up when a page loads using Selenium? So far, I have tried using the Robot class to press the escape key, but it only works 80% of the time. I have also experimented with Firefox prefere ...

Testing a function within a React functional component using jest.spyOn with React Testing Library can be accomplished with the following steps:

I'm currently working on a React component and I'm facing an issue with unit testing using React Testing Library. Specifically, I'm having trouble testing the handleClick function of the TestComponent using jest.spyOn(). Can anyone provide s ...