Rendering Objects with Three.JS in an AngularJS Directive

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:

  1. Adjusting the camera's point of view, position, and aspect ratio
  2. Increasing the size of the object
  3. 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();

      }

    };

  });

Answer №1

Your camera angle needs adjustment to make the object visible. Simply increase the value of z to 5.

The reason why camera.lookAt(scene); is not functioning properly is because you need to incorporate the position of the scene. Use camera.lookAt(scene.position); instead.

To see the updated code, click on this link.

Modifications made include:

camera   = new THREE.PerspectiveCamera(50, scope.width / scope.height, 1, 1000);

camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 5;

....
camera.lookAt(scene.position);

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

Uh-oh! It seems like there is a deployment error in NextJS on Vercel. The issue is that Nested

Suddenly, my middleware ceased to function properly during deployment. The error message states: > Build error occurred NestedMiddlewareError: Nested Middleware is not allowed, found: pages/_middleware Please relocate your code to a single file at /midd ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

Scrolling will only function properly on this page if you refresh it

I have a setup where buttons on my first page lead to specific elements on the second page. To achieve this, I pass the element IDs in the URL like so: mysite.com/secondpage/:promo1(/2/3, depending on the button clicked.) Upon landing on the second page, ...

The issue I'm facing is that the "background-image" is not resizing automatically when changing orientation in CSS on

I've encountered an issue with displaying an image in the DOM that is sized based on the screen height. While this setup works flawlessly on most browsers and devices I've tested, Safari iOS 7 seems to be causing some trouble. Specifically, in S ...

Select a checkbox automatically after receiving an ajax response

I am currently working with a form that contains multiple checkboxes like the one below: <label class="checkbox"> <input type="checkbox" id="user_ids_for_edit" name="user_ids_for_edit[]" data-toggle="checkbox" data-toggle="checkbox" value="14"&g ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Unlocking Secret Data with External JavaScript

Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML ...

Remove items from an array using JavaScript

My array, results = [duplicate, otherdup], holds a list of duplicates. Within my regular array, original_array = [duplicate, duplicate, duplicate, otherdup, otherdup, unique, unique2, unique_etc], how can I iterate through the results array and remove dup ...

Vuex data fails to update upon browser reload in Nuxt SSR

After explaining the bug, I discovered something interesting; Component codes async fetch(){ await this.$store.dispatch('bots/getBots') }, computed: { ...mapState('bots', ['bots']) }, Store codes export const state = () ...

What are the steps to utilize vue.js for dynamically adjusting my sidebar based on a URL input?

Greetings to the amazing community of Vue.js enthusiasts, I am a novice looking to develop a single-page web application using vue.js. This application will consist of a fixed header and dynamic body content that changes based on user interactions. Here&a ...

Expand Bootstrap accordion on hover

I have tried several examples that I discovered on Google and Stack Overflow, but none of them seem to work. So, I decided to attempt a different solution for opening the Bootstrap accordion on hover, however, it is not working as expected. Do you have any ...

Running Java applications on Amazon Web Services (AWS) hosting platform

I currently have 2 projects in progress. Developing a Spring Restful Webservice Building an AngularJS application For the database, I'm using MySQL. Although I am inexperienced with AWS, I am looking to host my applications using AWS. I need to de ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

Unable to transform undefined or null into an object within Next.js

Hi there! Currently, I am working on creating a login page using Next.js and next-auth. I have included the necessary providers in the providers array within [...nextauth].js. However, when I attempt to run the following code: import { getProviders, signIn ...

ng-repeat: Setting the default item as selected

I am having trouble initializing a list of items using ng-repeat directive. <div class="item" ng-click="selectedProject(fpItem)" data-id="{{fpProjectItem.id}}" ng-repeat="fpItem in fpItems"> <img src="{{fpItem.thumbnail}}" /> <span c ...

What causes the error "searchInput" to be undefined?

Currently, I am facing an issue while attempting to search for individuals stored in an array within the Redux store. Whenever I try to execute a search, an error is triggered with the following message: Cannot read property 'searchInput' of und ...

learn how to implement local storage for a to-do list application using JavaScript

How do I implement the storage property in this code snippet? The current code is not functioning correctly and resets after each page refresh. Please review my code at the following link: https://jsfiddle.net/74qxgonh/ let values = []; // Accessing Form ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

Can a FilePicker be Cleared Automatically through Code?

Currently, I am implementing an‘<input type="file" . . .’ to select files individually and then attach them to a table located right under the file picker. This functionality is quite similar to using the attachment button on a SharePoint form’s r ...

Saving the subtracted value from a span into a cookie until the checkbox is unchecked - here's how to

I am working on a piece of code that includes numeric values within a span. When the checkbox is clicked, it subtracts 1 from the main value, essentially reducing the total value. How can I achieve this so that even after the form is submitted, the deducte ...