I am currently in the process of integrating Three.JS into an AngularJS directive. Right now, my main goal is to create a proof-of-concept implementation that can serve as a template for a more complex directive in the future.
Currently, I am utilizing the link
function of the directive to set up the Three.JS scene and start the animation.
The scene is rendering properly, and the animation is functioning as expected. However, the object that I added to the scene is not visible.
I have tried:
- Adjusting the camera's point of view, position, and aspect ratio
- Increasing the size of the object
- Modifying the color of the object
I'm uncertain whether the object is simply out of view/invisible for some reason or if it's not actually present in the scene.
In the render
function, I used console.log
to confirm that the object was located in the scene.traversal
function call, and its rotation was being adjusted correctly.
I validated that the same code successfully renders and animates an object outside of this context.
Below is the full directive code, and you can access it on JSBin here.
angular.module('nxGeometry', [])
.directive('nxGeometry', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
// Scene variables
var camera, scene, geometry, renderer, material, object, container;
// Element dimensions
scope.width = element[0].offsetWidth;
scope.height = element[0].offsetHeight;
scope.objectColor = '#ffaa44';
scope.backgroundColor = '#333333';
// Initialization function
scope.init = function(){
container = angular.element('<div>')[0];
element[0].appendChild(container);
camera = new THREE.PerspectiveCamera(20, scope.width / scope.height, 1, 1000);
camera.position.x = 5;
camera.position.y = 0;
camera.position.z = 0;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry(1,1,1);
material = new THREE.MeshBasicMaterial({color: "#ffffff"});
object = new THREE.Mesh(geometry, material);
object.position.x = 0;
object.position.y = 0;
object.position.z = 0;
scene.add(object);
renderer = new THREE.WebGLRenderer();
renderer.setSize(scope.width, scope.height);
renderer.setClearColor(scope.backgroundColor);
container.appendChild(renderer.domElement);
}; // @end scope.init
scope.render = function(){
camera.lookAt(scene);
// Traverse the scene, rotate the Mesh object(s)
scene.traverse(function(element){
if(element instanceof THREE.Mesh){
element.rotation.x += 0.0065;
element.rotation.y += 0.0065;
}
renderer.render(scene, camera);
});
}; // @end scope.render
scope.animate = function(){
requestAnimationFrame(scope.animate);
scope.render();
};
scope.init();
scope.animate();
}
};
});