Error message "Uncaught TypeError: Cannot read property 'domElement' of undefined" occurred in webgl-template.html at line 69 in Three.js

I found this interesting code on

<!DOCTYPE html>
<!-- saved from url=(0056)https://www.benzedrine.ch/vistaprint/webgl-template.html -->
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <style>
        body {
            margin: 0px;
            background-color: #000000;
            overflow: hidden;
        }

        canvas {
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>

    <div id="container"></div>
    <div id="info">info</div>

...

        </script>

</body>

</html>

After running the code, I encountered an error message:

webgl-template.html:69 Uncaught TypeError: Cannot read property 'domElement' of undefined at init (webgl-template.html:69) at webgl-template.html:154

The problematic line in the code is Line 69:

controls = new THREE.TrackballControls(camera, renderer.domElement);

If anyone can assist me with resolving this issue, I would greatly appreciate it. Thank you!

Answer №1

The issue with the current code is that the variables are being used before they are initialized, resulting in an error stating that the property is undefined. In JavaScript, if you do not initialize a variable, it will have a value of undefined.

var foo; 
foo.bar; // This will throw an error because foo is undefined

In order for your example to work, you need to initialize the renderer and scene variables before using them.

Here is the corrected code:

function init() {

    scene = new THREE.Scene();
    scene.fog = new THREE.Fog(0xffffff, 1, 5000);
    scene.fog.color.setHSL(0.6, 0, 1);

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(scene.fog.color, 1);

    camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 5000);
    camera.position.set(411, 218, 559);

        
    controls = new THREE.TrackballControls(camera, renderer.domElement);
    ...

Just a reminder, if you do not have THREE.js locally, make sure to either download it or include the library via a URL like this:

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

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

How do I access a specific child from an object/element retrieved by using the elementFromPoint() method in Javascript?

Is there a method to extract the child element from an element or object retrieved by the function elementFromPoint(x, y); Consider the following scenario: var elem = document.elementFromPoint(x, y); Let's assume that the element returned and saved ...

Highcharts plots only appear once the browser window is adjusted

Having some issues while testing out the Highcharts javascript charting library on a specific page. The problem I'm encountering is that none of the data appears until I adjust the browser's size slightly. Prior to resizing, the tooltip does dis ...

The call stack limit has been exceeded in VueJS/VueX

I'm currently developing a Vue project with Vuex for state management. However, I encountered a Maximum call stack size exceeded error in my console when attempting to bind actions and getters in my component using mapActions and mapGetters. I'm ...

What is the best way to interpret and execute conditions specified within strings like "condition1 and condition2"?

Received a JSON file from an external source with various conditions that need to be tested, either in real-time or through conversion. Imagine having an instance of a class called Person, with attributes {age: 13, country: "Norway"}, and an ext ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Create a JavaScript function that adds two separate events to an input field

I need assistance with adding two events on an input field: onkeyup and onchange. The goal is to prevent users from entering characters other than numbers, as the field is for zip code entry. Currently, only one event is working - either keypress or onchan ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

What is the best way to make a div element take up the entire page

Is there a method to enlarge one div container to cover the entire page, similar to a zoom effect, without displaying any other elements on the page, and then enable the user to return to the normal view by pressing escape or clicking outside of the div ...

Encountering a NoSuchElementException when transitioning from frame[0] to window[1] in Firefox GeckoDriver using Selenium with Python

Encountered an issue with the Firefox GeckoDriver browser where I receive an error stating `element not found`. The problem arises when I navigate from window[1] to frame[0], back to window[1], and then attempt to click the close frame button. I prefer u ...

Using React hook form to create a Field Array within a Dialog component in Material UI

I have a form with custom fields added via Field Array from react-hook-form, and everything is functioning properly. However, I recently implemented drag and drop functionality for the property items to allow reordering them. Due to the large number of fie ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Issues with grunt - Alert: Task "ngAnnotate:dist" has encountered an error. Proceed using --force option

Encountering an unexpected issue with a Grunt task that previously ran smoothly. The error message is as follows: Running "ngAnnotate:dist" (ngAnnotate) task Generating ".tmp/concat/scripts/scripts.js" from: ".tmp/concat/scripts/scripts.js"...ERROR >& ...

Displaying data from an array using jQuery or JavaScript loop

I have a scenario where I have multiple links on a webpage that have been converted into an array using jQuery. The idea is that when a user clicks on a "load more" button, I want to create a <ul> element with 4 images inside it (or fewer if there ar ...

Most efficient method to retrieve a specific element from an array without the need for iteration

Within one of the controllers in my Angular application, I have set a variable like this: SomeService.get({}, function(data){ // This assigns xyz as the data list retrieved from the // resource within the controller's scope $scope.xyz = ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

What is the process for running "node server.js" within codelab?

I am currently going through a codelab tutorial on Bitbucket at this link After installing node.js for the first time, I encountered an error when trying to run the server.js file: node server.js The error message "node: Command not found" appeared even ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Why is req.app.post(...)create_event not functioning as expected?

Currently, I'm utilizing axios, node.js, express.js, and SQL to send a post request to my database. However, each time I attempt to do so, I encounter an error message stating: "TypeError: req.app.post(...).create_event is not a function". I've b ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

Using ng-model within ng-repeat for data binding in AngularJS

My challenge is to connect a model called 'User' to a series of input fields. Since I don't know the specific fields in advance, I need to write generic code that dynamically sets up the form based on the available fields. <script> ...