Why don’t you bundle all the unique variables inside a JavaScript class? A class would be cleaner to manage because it compartmentalizes all its variables in its own scope, instead of having to worry about managing unique global variables. Here’s a quick example:
class View {
// Init all variables in its isolated scope
constructor(objURL) {
this.camera = new THREE.PerspectiveCamera();
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer();
// Load custom object
this.loader = new THREE.GLTFLoader();
this.loader.load(objURL, function(glb){
const obj = glb.scene0.children[0];
this.scene.add(obj);
});
this.update();
}
update() {
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(this.update.bind(this));
}
}
You only need to define this class once to build your boilerplate scene setup. Then you can write a PHP loop that creates multiple instances of the same class, with a different URL to load:
// Write PHP loop that outputs the following:
var view1 = new View("folder/obj1.gltf");
var view2 = new View("folder/obj2.gltf");
var view3 = new View("folder/obj3.gltf");
var view4 = new View("folder/obj4.gltf");
var view5 = new View("folder/obj5.gltf");
Now all you have to manage is each view#
variable, instead of its individual scenes, cameras, renderers, etc. If this is your first time writing a class, here’s a quick overview from MDN.
I apologize if my first answer suggested creating so many unique variables for each object, I didn’t expect the PHP loop to get so out of control! This approach should be easier to manage.
PS: The only caveat with class
is that it’s not supported in IE. If you need to support IE, I recommend you use the similar (but more verbose) function + prototype
approach explained here.