Enhance Three.js 3D model visuals with textured surfaces using Fabric.js canvas as a dynamic texture

Exploring the world of Three.js for the first time, I am embarking on a project that involves leveraging a pre-existing 3D model and altering one of its materials to utilize a Fabric.js canvas as its texture. However, I've hit a roadblock where the texture absorbs the color of the canvas, but any images I attempt to incorporate remain invisible. Below is a snippet of my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        body { margin: 0; }

        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1;
        }
    </style>
</head>
<body>
    <div id="controls">
        <div class="colorPicker"></div>
        <canvas id="c"></canvas>
        <button id="clear">Clear</button>
        <input type="file" id="file">
    </div>
    
    <!-- Additional scripts and functionalities -->

Despite my efforts, the material fails to update upon uploading an image.

Answer №1

The challenge was not in the coding itself, but rather in the 3D modeling aspect. Upon making adjustments to the model, I discovered that it lacked UV mapping, which is essential for Three.js to correctly apply textures to the material. Here is the finalized code that resolved the issue:

function loadModel() {
    const loader = new THREE.GLTFLoader();
    loader.load('assets/models/2x2.glb', function (gltf) {
        model = gltf.scene;
        model.scale.set(0.001, 0.001, 0.001);
        model.position.set(0, 0, 0);

        model.traverse(function (child) {

            if (child.isMesh) {

                if (child.material) {
                    if (child.material.name == "mat14.003") {
                        const basicMaterial = new THREE.MeshBasicMaterial({
                            map: child.material.map, // Applies the texture of the original material if it exists
                            side: THREE.DoubleSide // Applies texture to both sides if necessary
                        });

                        child.material = basicMaterial;

                        child.material.map = texture;
                        child.material.map.wrapS = THREE.RepeatWrapping;
                        child.material.map.wrapT = THREE.RepeatWrapping;
                        child.material.map.needsUpdate = true;
                    }
                }
            }
        });
        
        scene.add(model);
    }, undefined, function (error) {
        console.error(error);
    });
}

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 error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

Alter the class following modifications to the list

https://i.stack.imgur.com/QZob0.pngIn my dual list, the data is displayed in a ul li format fetched from a JSON file. Users can move items between the two lists. However, I am facing an issue where I want to apply a property that only displays content with ...

Accessing the "current" color in a FragmentShader with ThreeJS

Recently delving into ThreeJS, I have a collection of instanced meshes and I am utilizing setColorAt's for each of them. These meshes have materials set to a ShaderMaterial with both a vertexShader and fragmentShader. I am interested in experimenting ...

I'm trying to create a horizontal list using ng-repeat but something isn't quite right. Can anyone help me figure out

Feeling a bit lost after staring at this code for what seems like an eternity. I'm trying to create a horizontal list of 2 image thumbnails within a modal using Angular's ng-repeat. Here's the HTML snippet: <div class="modal-body"> ...

Angular Alert: [$injector:modulerr] Unable to create the angularCharts module because: Error: [$injector:nomod]

Although this question has been asked multiple times, the standard solutions provided did not resolve my issue. Therefore, I am sharing my code along with the error in hopes that it will be self-explanatory. Error: Uncaught Error: [$injector:modulerr] Fa ...

Tips for downsizing a large image to fit into a smaller area

I am working on a page layout that features a small circular navigation element. However, I am facing an issue with fitting a large picture within the boundaries of this small circle without it overflowing and causing alignment problems. Does anyone have ...

Guide to discovering an almost ascending sequence in an Array

I recently encountered a challenging algorithm problem that I need help with: "I have a sequence of integers stored in an array. My task is to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element f ...

Invoke a Node.js script from a Spring Boot application to pass a Java object to the script. The script will modify the object and then return it back to the originating class

class Services { Address address = new Address(....); /* Invoke NodeJs script and pass address object In the js script modify address object var address = getAddress() Modify address object Return address obj ...

Creating a well-aligned form using Material-UI

Exploring Material-UI for the first time! How can a form be built where certain fields are arranged horizontally, others stacked vertically, and all aligned perfectly both vertically and horizontally? Check out this example image: https://i.sstatic.net/5R ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Terminate the rethinkdb data stream

Currently delving into the world of RethinkDB and am eager to utilize the changes() method to fetch a changefeed. While I've figured out how to initiate them, the documentation doesn't quite explain how to halt a changefeed. Is it sufficient to ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

Setting the height of Material-UI TreeView

Looking for advice on how to set a fixed height or dynamically adjust the height of a material-ui TreeView to fit the display? https://i.sstatic.net/40Qlv.png I'd like a scrollbar to appear when the TreeView content reaches a height of 100 pixels, f ...

I'm having issues with my countdown timer

Here is some of my JavaScript code: var run; var countdown; var count =14; var curImage = 1; function startAdPage() { run = setInterval("changeAd()"5000); countdown = setInterval("startCountdown()",1000); } function changeAd { switch (curImage) { case 1: ...

When I make a post request, I receive a response in the form of an HTTPS link, but it is not redirected to

I'm making a post request and receiving the response as follows: " [Symbol(Response internals)]: {url: 'https://login.somenewloginpage'}" My intention is to open a new page using that URL, but unfortunately it does not redirect t ...

Traverse a tree structure of nested child objects in an Angular template using a JavaScript

Check out the Javascript object below: { "id": "1554038371930_ajhnms9ft", "name": "CPS", "nodes": [ { "id": "1554038905938_le34li2cg", "name": "Consumer Journey", "nodes": [ { ...

Tips for avoiding the 'ResizeObserver loop finished with unhandled notifications.' error when using React with mui/material/Table

This is our current code snippet: import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableC ...

JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented mom ...