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!