Applying a textured effect to a mesh in Three.js using JSON

When using THREE.js, I am facing difficulties loading a texture onto a mesh created from a JSON model. The code snippet below demonstrates loading a simple cube from models/cube.json:

function loadRabbit()
{
    // Load the Rabbit JSON data using a THREE loadTexture

    var loader = new THREE.JSONLoader();
    loader.load( "models/cube.json", rabbitLoaded );  // Calls rabbitLoaded on completion
    //loader.load( "treehouse.json", rabbitLoaded );  // Calls rabbitLoaded on completion
}

function rabbitLoaded( geometry, materials ) {
    // Called when rabbit dataset loaded asynchronously
    console.log("rabbit Loaded !!");

    var texture = THREE.ImageUtils.loadTexture ("assets/textures/general/weave_512x512.jpg")
    var meshMaterial = new THREE.MeshBasicMaterial({color: 0x363cc9});
    meshMaterial.map = texture;


    // create the rabbit. make global
    var rm = new THREE.Mesh(geometry, meshMaterial);

    rabbitMesh = rm;
    spotLight.target = rabbitMesh;
    spotLight3.target = rabbitMesh;
    scene.add( rabbitMesh );
}

If line
//meshMaterial.map = texture;
is commented out, it works fine, with a plain blue cube rotating in the scene. And elsewhere in the code I create a sphere:

function makeMarkerSpheres(size) {
    // Creates a 'marker' sphere in red, to help locate position in 3D. Not used in production.
    var sphereGeo = new THREE.SphereGeometry(size, 32, 32);
    var texture = THREE.ImageUtils.loadTexture ("assets/textures/general/weave_512x512.jpg")

    var sphereMatl = new THREE.MeshBasicMaterial({color: 0xcd9141});
    sphereMatl.map = texture;
    var sphere1 = new THREE.Mesh(sphereGeo, sphereMatl);
    sphere1.position.set(1,1,1);
    return sphere1;
}

This function works perfectly, creating a rotating cube with a coarse basket weave texture. However, the code at the top produces an error (in the browser console log):

[.WebGLRenderingContext-0x7ffd54a5e5d0]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1

The content of cube.json is as follows:

` 
{
"metadata" : {},
"scale" : 0.5,
"materials": [  {
    "DbgColor" : 15658734,
    "DbgIndex" : 0,
    "DbgName" : "default",
    "vertexColors" : false
    }],
"vertices": [-3,3,-3,3,3,-3,-3,-3,-3,3,-3,-3,-3,3,3,3,3,3,-3,-3,3,3,-3,3],
"faces": [0,0,1,2,0,3,2,1,4,4,6,7,4,5,4,7,0,1,5,3,0,5,7,3,0,0,2,4,0,4,2,6,0,1,4,5,0,1,0,4,       0,6,2,7,0,2,3,7],
"morphTargets": [],
"normals": [],
"colors": [],
"uvs": [[]]
}`

I believe there might be something crucial missing from the JSON data, but I'm unsure of what it could be. Any assistance would be greatly appreciated.

You can find the complete code on Bitbucket.

Answer №1

When working with a json-loaded model in order to apply a texture, it is crucial that the json file includes UVs.

Version r.71 of three.js

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

Problem encountered with Terrain Detection with Three.js

After generating a terrain using a heightmap in Three.js, I'm utilizing mrdoob's misc_controls_pointerlock for movement and collision. However, adding objects.push(terrainobj); causes the performance to drop significantly to 3fps (from around 60) ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Modifying the value of an HTML5 input type 'color' using JavaScript

In the image, there are pencil and eraser buttons. I would like the input value to change to black when the pencil button is clicked, and white when the eraser button is clicked. Here's what I've tried: <button onclick="$('#color-select& ...

Exploring Node's Configuration File Reading Process

Trying my best to provide all the details for my question. Being a newbie to NodeJS, I appreciate your kind guidance :D In the process of developing an application in Node, focusing on enabling users to view stats regarding their Plex Media Libraries. The ...

What are some methods for creating a more affordable sphere in aframe/three js?

In my VR application, I am currently using the aframe <a-sphere> element to render spheres, but it is creating a large number of triangles in my scene, causing a drastic drop in performance with frame rates down to the teens. Is there a more effici ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

Tips for adjusting the height of both an iframe and a div to fit perfectly at 100% combined

Struggling to make an iframe and div both have 100% full height on the page? I need a footer menu with 280px height, leaving the rest of the page for the iframe. After extensive research, it seems like jQuery might be necessary as CSS Flex didn't wor ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...

Error: The specified module 'sqlite' does not have an export named 'default' as requested

Having some difficulty with importing sqlite into my project. When I add this line: import sqlite from 'sqlite'; An error occurs: file:///D:/WebPro/WebProg/cwCode/dbInteract.js:2 import sqlite from 'sqlite'; ^^^^^^ SyntaxError: ...

Refresh the content of a div showcasing live Twitter updates automatically

Currently, I am experimenting with the Twitter APIv1.1 and am working on implementing a box that will showcase my most recent tweets. You can view the progress here: However, my goal is to have this box update automatically whenever I tweet. As a beginner ...

Is it possible to have the soft keyboard automatically appear when the page loads?

On an HTML5 website, I have an input element and I want the soft keyboard to automatically appear and focus on that input element. I attempted to use the 'autofocus' attribute on the 'input' element, but this only focused on the element ...

Click to save image using jQuery

I am trying to implement a feature where clicking on an image allows users to download it. I am using the download attribute for this purpose. <a href="http://mysite.ru/userfiles/certificate_2.png" class="download-certificate-link" data-title="certific ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Error: The module PosModel is not defined

Recently, I took over the responsibility of working on the models.js file for the point_of_sale module. My task was to add a new model by integrating the following code: openerp.dewieuw = function(instance, local) { //module is instance.point_of_sale var ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

Unable to consistently select a radio button via code across different browsers

Is there a way to automatically select a radio button based on the URL path? $(document).ready(function () { function checkRadioBasedOnUrl() { var urlPath = window.location.pathname.split("/"); console.log(urlPath); // ["", "tradeshow ...

Trigger click events based on specific coordinates x and y in Fabric.js

While working on my project, I utilized three.js and fabric.js to manipulate textures on a 3D model. I managed to synchronize coordinates on the model with coordinates on the canvas in fabric js. However, I encountered an issue with simulating click events ...

What is the best way to avoid multiple triggers of an event listener in a Vue Js Component?

When I use an event listener to call a specific function, it behaves strangely. Here is the code snippet: mounted() { window.addEventListener("message", this.call); }, methods: { call(e){ if (e.data === "test"){ ...