Learn how to showcase a sprite in webgl using three.js without encountering any errors like "Uncaught TypeError: Cannot read property 'x' of undefined" during rendering

My journey with three.js has just begun.

First, I decided to experiment with the code provided in this resource: Creating-a-scene

Next, I attempted to incorporate a sprite using the code from this reference: Sprite

Unfortunately, my efforts were met with an error message:

Uncaught TypeError: Cannot read property 'x' of undefined
    at SpritePlugin.render (three.js:6973)
    at WebGLRenderer.render (three.js:21007)
    at render (sprite.html:43)

The html file containing the possible mistake can be found here:

Could someone please assist me in identifying where I went wrong? Here is the code snippet I used:

<html>
    <head>
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="https://rawgithub.com/mrdoob/three.js/master/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );
            // instantiate a loader
            var loader = new THREE.TextureLoader();
            //allow cross origin loading
                //loader.crossOrigin = '';
            // load a resource
            loader.load("https://codefisher.org/static/images/pastel-svg/256/bullet-star.png");
            var spriteMaterial = new THREE.SpriteMaterial( { map: loader, color: 0xffffff } );
            var sprite = new THREE.Sprite( spriteMaterial );
            sprite.scale.set(200, 200, 1);
            scene.add( sprite );
            camera.position.z = 2;
            var render = function () {
                requestAnimationFrame( render );
                renderer.render(scene, camera);
            };
            render();
        </script>
    </body>
</html>

Answer №1

To resolve the issue, I recommend utilizing the code snippet provided below:

let icon = new Image();
icon.src = "https://example.com/image.png";

let material = new THREE.SpriteMaterial({ map: new THREE.Texture(icon), color: 0xffffff });

Additionally, it is imperative to include the requestAnimationFrame function for smooth rendering.

Answer №2

Although it may seem simple at first, displaying a basic sprite with three.js and WebGL can be quite challenging.

I encountered numerous errors along the way and had to combine two different solutions in order to succeed:

  • WebGL - not loaded texture
  • Three.js - how to wait for an image to be loaded?

    1. If you're not running on a server, you'll need to convert the image to binary format.
    2. You must also ensure that the image is fully loaded before proceeding.

In the end, the code below proved to be effective:

<html>
    <head>
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="https://rawgithub.com/mrdoob/three.js/master/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
            camera.position.set(0, 10, 100);
            camera.lookAt(new THREE.Vector3(0, 0, 0));
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            var material = new THREE.LineBasicMaterial({ color: 0x0000ff });
            var geometry = new THREE.Geometry();
            var a = 5;
            geometry.vertices.push(new THREE.Vector3(-a, 0, 0));
            geometry.vertices.push(new THREE.Vector3(0, a, 0));
            geometry.vertices.push(new THREE.Vector3(a, 0, 0));
            geometry.vertices.push(new THREE.Vector3(0, 0, -a));

            var line = new THREE.Line(geometry, material);

            scene.add(line);

            var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABISURBVDhPzc1bCgAgCETR9r9poxynEHoIEp0vLS4WCWpBMfq09yYI8QFuTfBhlgFXHSgj4KB0pYzAwYfx+9FVgFv92ifBIFIBJq9zqYwecEQAAAAASUVORK5CYII=";
            var loader = new THREE.TextureLoader();
            var spriteMaterial = new THREE.SpriteMaterial( { color: 0x00ff00 } );
            var spriteMaterial;
            loader.load(img,
                function(texture)
                    {
                        spriteMaterial.map = texture;
                        spriteMaterial.needsUpdate = true;
                    }

                );
            var sprite = new THREE.Sprite( spriteMaterial );
            sprite.scale.set(6, 6, 1);
            sprite.position.set( 0, 6, -6 );
            scene.add( sprite );

            var render = function () {
                requestAnimationFrame( render );
                renderer.render(scene, camera);
            };
            render();
        </script>
    </body>
</html>

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 to attach a custom event to a nested component in Vue.js when using a for loop

I have implemented a system using three single-file-components. ParentVariation.vue VariationInfo.vue Childvariation.vue In this setup, the variation-info child component emits a MarkedFilled event which is then caught by the ParentVariation component. ...

Unlock the tab element within a modal using ng-bootstrap

I am currently encountering an issue with ng-bootstrap in Angular 2. I am unable to access the #tabs variable from my component using @ViewChild. This problem arises only when I utilize the tab directive within the modal directive. Here is a snippet of m ...

Using `getJson` to parse the tree structure

I am currently working with a JSON file that contains order data. The structure of the JSON file is as follows: { "orders": [ {"name": "Peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140110011624050b0 ...

What causes programming languages to exhibit such behavior in the absence of any established hierarchy?

I was puzzled to discover that in Python and Javascript, when using this type of conditional statement, the logic seems off. If we add console.log statements in each condition, it appears that the comparison should be false != true, meaning that the code s ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Guide to inserting images into CKEditor using ReactJS

I am currently developing a project using Reactjs with the "nextjs" framework. I am facing an issue with the Ckeditor where I am unable to insert or add images. Can anyone guide me on how to resolve this? Below is the code snippet from my "Ckeditor.js" fil ...

Different language implementations of AES ECB mode yield varying outputs

I have encountered an issue while attempting to transfer an AES encrypted string from a python script to a nodejs script using ECB mode. The relevant code snippets are as follows: Firstly, I utilize pycryptodome to encrypt a string with AES: from Crypto.C ...

Is it possible to create videos in JavaScript by programming pixel by pixel?

I'm currently in the process of converting a python program, utilizing OpenCV, to javascript/html. This program generates a video where pixel colors are determined by a random function of its coordinates and frame number. While I have successfully cr ...

The data in the second run of the jQuery datatable does not refresh successfully

I have encountered an issue while trying to load data from the server. It works perfectly on the initial load, but upon reloading, it fails to function. Please bear with me as this is a legacy project. Even after attempting a normal call and refreshing th ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Having trouble with CSS text-align right not functioning properly? Here's how you can fix it

<div style="text-align: left;width: 21cm;"> <h4 style="text-align: center;font-weight: bold;font-size: 20px;margin: 0">Tax Invoice(Center) <span style="text-align: right;"> For Customer(Right)</span></h4> </div> I n ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...

Problem with loading CSS and JavaScript files on Node.js server

Recently, I delved into learning Node.js and created a basic server setup like this: // workspace const p = document.querySelector('p'); p.textContent = 'aleluja'; html { font-size: 10px; } body { font-size: 2rem; } <!DOCTYPE ht ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

Is there a way to identify when a <td> element in a table is modified using JavaScript?

Currently, I am working on a Table where the values in the <td> elements change dynamically based on user input from a form. To achieve this, I am utilizing Tangle for creating a reactive document. I am facing a challenge where I need to detect any n ...

contrasting module export approaches

Let me clarify that my query does not revolve around the disparity between module.exports and exports. Instead, I am interested in understanding the contrast between exporting a function that generates an object containing the functions to be shared upon i ...

Using multiple where clauses in Firebase for advanced querying

Let me explain the scenario. Within my database, there is a Users collection. Some users have a property called userType, while others do not. The values for userType can either be person or company. I want to retrieve only the users that have the userTyp ...