Unable to perform 'texImage2D' on 'WebGLRenderingContext'. Encounter an issue when generating canvas texture

My goal is to wrap text around the sleeve of a glTF shirt object, so I created a mesh on top of the sleeve using blender. I then added a canvas texture to the mesh and attempted to render text on it, but unfortunately, I encountered an error:

https://i.sstatic.net/sbVZ8.png

Below is the code I used:

loadModel(model, callback) {
        this.loader = new GLTFLoader();
        this.loader.setCrossOrigin('anonymous');
        this.loader.load(model, (gltf) => {
            if (typeof callback === 'function') {
                callback(gltf.scene);
            }

            this.scene.add(gltf.scene);
        });
    }

loadModel() {
            this.isLoaded = false;

            this.scene.loadModel('model10/V Shirt text.gltf', (model) => {
                model.name = 'shirt';
                
                // Iterate through the model's children
                model.traverse((child) => {
                    if (child instanceof THREE.Mesh) {
                        // Reset original material
                        child.material.map = null;
                        if (child.name = 'Text') {
                            let canvas = document.createElement('canvas');
                            canvas.height = 100;
                            canvas.width = 100;
                            let context = canvas.getContext('2d');
                            context.fillStyle = 'black'
                            context.font = '100pt Helvetica'
                            context.fillText('Hello', 10, 90);
                            const texture = new THREE.CanvasTexture(context);
                            const material = new THREE.MeshBasicMaterial({
                                map: texture
                            })
                            child.material.map = texture;
                            child.material.map.needsUpdate = true;
                        }
                        // Create wireframes
                        // this.createWireframe({ mesh: child });

                        // Push to local array
                        this.objects.push(child);
                    }
                });

Answer №1

You can create canvas textures by using the following code:

Here is an example of how to create a canvas texture:

const texture = new THREE.CanvasTexture(canvas);

When creating canvas textures, remember to pass the canvas itself and not the rendering context.

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

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

Dynamic Next.js Redirects configured in next.config.js

After building the project, I am looking to update Redirects routes. Currently, we have redirect routes on our BE Api. My goal is to fetch these redirect routes dynamically and implement them in next.config.js. Here is what I have attempted: const getUrls ...

Exploring FileReader and DOMParser for AngularJS applications

I have a user uploaded file using AngularJS and would like to manipulate the file contents using XML. Unfortunately, I am facing an issue with the DOMParser recognizing the text file. index.html <div ng-controller = "myCtrl"> <input type ...

A step-by-step guide on importing several jpg texture files in THREE.js using obj and mtl files

Using THREE.js, it's simple to load tga or dds files as textures when loading obj + files. For example, in their obj + mtl example (): // Add tga texture files THREE.Loader.Handlers.add( /\.tga$/i, new THREE.TGALoader() ); However, what if you ...

To enable RTL in TextField, please note that the JssProvider is only available in "react-jss/src/JssProvider" and not in "react-jss/lib/JssProvider"

Seeking help to convert LTR to RTL in the following code: <TextField id="date" label="EmployeeDate" type="date" onChange= ...

Having trouble with Javascript's JSON.stringify or PHP's json_decode?

I am attempting to send an array from JavaScript to PHP. JavaScript: var json = JSON.stringify(extraFields); url += "&json="+json; PHP: $json = json_decode($_GET['json'], true); foreach($json as $K=>$V){ echo "json".$K . "=" . $V ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully. Below is the ...

Regular expression for parsing any CSS font properties

Does anyone have a reliable regex to break down a css font string into its individual components? 12px arial italic bold sans-serif 12px/50px verdana etc ...

"Steps for implementing a multiselect feature with checkboxes, including the ability to check all and uncheck all, in a React application

After creating a custom component for selecting multiple options and adding a check all feature, the challenge arises when needing an uncheck option. Solution? Implementing an uncheck all feature alongside the select all functionality, but how to modify th ...

Searching for values in nested arrays using lodash.find

Presented below is an array where I aim to employ lodash for item search: [ { "itemA": "apple", "itemB": [ { "itemC": "1", "itemD": "red apple" }, { "itemC": "2", "itemD": "green apple" }, ...

Acknowledging client after client to server POST request has been successfully processed in Node.JS

I've been working on responding to client-side requests with Node.JS. While searching, I came across a helpful article on calling functions on the server from client-side JavaScript in Node JS. However, I'm having trouble implementing it in my pr ...

The imported package is not functioning properly within the project

I've recently developed a Typescript Package and I want to test it in an application before publishing it on NPM. The main file (index.ts) of the package is structured like this => import Builder from './core/builder'; export default ...

Having trouble setting the audio source path in a handlebars file

homepage.html <script> function playAudio(audio_src){ console.log('audio src: ' + audio_src); var player = document.getElementById('player'); player.src = audio_src; player.load(); player.play(); return f ...

How to utilize a Multidimensional JSON Array in a jQuery Function

I'm struggling with passing a PHP array to a jQuery function and accessing values from a multidimensional JSON array. When I try to retrieve the value of 'lat' using the code below, I receive an error stating Cannot read property 'lat&a ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...

Combining AddClass and RemoveClass Functions in Mootools Event Handlers

I am currently in the process of creating a CSS animation, and one aspect involves changing the class name of the body at specific intervals. Since I am relatively new to Mootools (and JavaScript in general), my approach has been to add/remove classes to ...

What is the best way to get the number of populated children in a Mongoose schema?

Hello all, I am just beginning to learn about MongoDB and Mongoose. Does anyone know of a simple method to count the answers for each topic after using the population method? var query = Topic.find({}); query.select("title answersRef"); query.populate({p ...

Array buffers are scheduled by BinaryJs and the Audio API

My node.js server is streaming some ArrayBuffers: var BinaryServer = require('binaryjs').BinaryServer; var fs = require('fs'); var server = BinaryServer({port: 2000}); server.on('connection', function(client){ var file = f ...