Error: An uncaught TypeError has occurred in a TypeScript script using three.js, stating that it is unable to read the 'position' property of

I'm encountering a small issue with initializing the camera position in my three.js project written in TypeScript. The browser console is showing me an error message: Uncaught TypeError: Cannot read property 'position' of undefined. Below is the code from my app.ts file:

///<reference path="Lib/three.d.ts">
class Rendering {
    camera: THREE.PerspectiveCamera;
    scene: THREE.Scene;
    renderer: THREE.CanvasRenderer;
    windowHalfX: number;
    windowHalfY: number;

    constructor() {
        this.windowHalfY = window.innerHeight/2;
        this.windowHalfX = window.innerWidth / 2;
    }

    public init() {
        var container = document.createElement('div');
        document.body.appendChild(container);

        this.camera = new THREE.PerspectiveCamera(60, this.windowHalfX / this.windowHalfY, 1, 1000);
        this.camera.position.y = 100; // ISSUE WITH READING POSITION PROPERTY
        this.camera.position.z = 200;
        this.scene = new THREE.Scene();
        this.renderer = new THREE.CanvasRenderer();
        this.renderer.setSize(this.windowHalfX*2, this.windowHalfY*2);
        container.appendChild(this.renderer.domElement);
        var cubeGeometry = new THREE.CubeGeometry(150, 150, 150);
        for (var i = 0; i < cubeGeometry.faces.length; i += 2) {

            var hex = Math.random() * 0xffffff;
            cubeGeometry.faces[i].color.setHex(hex);
            cubeGeometry.faces[i + 1].color.setHex(hex);

        }
        var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, overdraw: 0.5 });
        var cube = new THREE.Mesh(cubeGeometry, material);
        cube.position.y = 150;
        this.scene.add(cube);
    }
    public render() {
        this.camera.lookAt(this.scene.position);
        this.renderer.render(this.scene, this.camera);
    }
}

Does anyone have any suggestions on how to resolve this error?

Answer №1

The primary reason behind this issue is the absence of the PerspectiveCamera JavaScript...

Simply including three.js from the Three.JS zip file is not sufficient for your web page.

To ensure all necessary components, including the PerspectiveCamera, are included, it is recommended to use the minified three.js file available at:

This single minified script bundles all required components together for seamless integration.

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

Is there a way to retrieve the operating system user name using Angular 6?

In order to ensure security for hospital staff using our app on Chromebooks, I am looking to retrieve the OS username and send it to a .NET web API. This API will then check if the user exists in the active directory and return their information. ...

The default value for the ReturnType<typeof setInterval> in both the browser and node environments

I have a question about setting the initial value for the intervalTimer in an Interval that I need to save. The type is ReturnType<typeof setInterval>. interface Data { intervalTimer: ReturnType<typeof setInterval> } var data : Data = { ...

Error message: Typescript and Styled-Component conflict: GlobalStylesProps does not share any properties with type { theme?: DefaultTheme | undefined; }

I've encountered an issue while passing props inside GlobalStyles in the preview.js file of my storybook. The props successfully remove the background from the default theme, but I'm receiving an error from Typescript: The error message states " ...

Collaborating on a project that has been developed using various editions of Typescript

Currently, I am part of a team working on a large project using Typescript in Visual Studio. As we have progressed through different versions of the project, we have encountered an issue with versioning the installed TypeScript within Visual Studio. Situa ...

Angular Custom Validator Error (Validation function must either return a Promise or an Observable)

I created a personalized validator for the phone field but I'm encountering an issue The validator should be returning either a Promise or an Observable. Basically, I just want to check if the phone number is less than 10 characters. HTML Cod ...

Please indicate the Extended class type in the return of the child Class method using TypeScript 2.4

I'm currently in the process of upgrading from TypeScript version 2.3.2 to 2.4.2. In the previous version (2.3), this piece of code functioned without any issues: class Records { public save(): Records { return this; } } class User extends ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

Optimizing image imports through treeshaking while integrating Typescript

One of my components has a structure similar to this: import foo from "./assets/foo.svg"; import bar from "./assets/bar.svg"; const icons = {foo, bar}; type IconTypes = "foo" | "bar"; type IconProps = { ic ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

Just starting out with Angular and struggling to understand how to fix the TS(2322) error

Main Code: export class TodosComponent implements OnInit{ todos!: Todo[]; localItem: string; constructor(){ const data = localStorage.getItem("todos"); this.localItem = data; if(this.localItem == null){ this.todos = []; } ...

Upon executing the tsd install and tsd query commands, a message indicating 'no results found' was displayed

Whenever I run these commands in Git Bash on Windows tsd query angular-material tsd query angular tsd install angular angular-material I always receive the message ">> zero results" ...

Top method for extracting mesh vertices in three.js

Being new to Three.js, I may not be approaching this in the most optimal way, I start by creating geometry like this: const geometry = new THREE.PlaneBufferGeometry(10,0); Next, I apply a rotation: geometry.applyMatrix( new THREE.Matrix4().makeRotation ...

Creating a distinct Output type in Typescript to avoid any confusion between Output arguments and Input arguments

Inspired by C#, I am looking to define the following: type FunctionOutput<T> = T; // This is a basic implementation that needs improvement type Result = {result: number}; function myFun(a: number, b: number, c: FunctionOutput<Result>) { c.r ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case: customer/urls.ts namespace Portal { export cl ...