Wordpress integration

I’m just trying to implement a simple test scene in WordPress.

If I implement this in the header of my child theme, I can render the scene, but it is not animated. The timer doesn’t seem to be working. What can that be?

When I insert the test scene into my WPBakery Page Builder using raw js, the scene is rendered and the timer works too, but it is always rendered after the footer, regardless of whether I insert it before the content. Does anyone have any experience with this?

My test code looks like this:

	<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script>

	var camera, scene, renderer;
	var geometry, material, mesh;

	function init() {

		camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10 );
		camera.position.z = 3;

		scene = new THREE.Scene();
		scene.background = new THREE.Color( 0xffffff );

		geometry = new THREE.SphereGeometry( 1 );
		material = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true } );

		mesh = new THREE.Mesh( geometry, material );
		scene.add( mesh );

		renderer = new THREE.WebGLRenderer( { antialias: true } );
		renderer.setSize( window.innerWidth, window.innerHeight );
		document.body.appendChild( renderer.domElement );				
				
	}

	function animate( time ) {

		mesh.rotation.x = time * 0.0005;
		mesh.rotation.y = time * 0.001;

		renderer.render( scene, camera );
		requestAnimationFrame( animate );

       }

	init();
	requestAnimationFrame( animate );

</script>

The reason why it renders after the footer, is because the WP footer is written to the doc before your script executes the line

document.body.appendChild( renderer.domElement );

I haven’t use WP for many years, so I don’t know what your options are. But maybe you can insert the renderer.domElement into the html doc somewhere explicitly, such as an existing canvas element, rather than appending to the end.

eg,

const existingCanvasElement = document.getElementById("id-of-an-existing-canvas-in-the-html-doc")
const renderer = new THREE.WebGLRenderer({ canvas: existingCanvasElement })

Thanks a lot, I will try that.

Please could you post your findings - did seanwasere’s solution work?

he was pasting a script in the header and invoking it immediately which usually doesn’t work.

There are many options that will work, probably the simplest is:

document.addEventListener('DOMContentLoaded', () => {
  // your script here
})

so it always begins after it’s loaded.

If anyone is interested in simple threejs / Wordpress galleries, I also have a plugin:
https://wordpress.com/plugins/threepress

The Scenes you make with the shortcodes are available to global scope, so it could potentially save a lot of the boilerplate of instantiating threejs scenes, but ymmv - it’s not really intended for custom scenes yet, more for people uploading one-off models.

1 Like