Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head):

  window.onload = function() {
var container, stats;
var camera, scene, renderer;

var mouseX = 0, mouseY = 0;

var windowHalfX;
var windowHalfY;

init();
animate();


function init() {

    container = document.getElementById('mon_canvas');

            width = container.width;
            height = container.height;
            alert("Width :"+width+",Height :"+height);

           windowHalfX=width/2;
           windowHalfY=height/2;

    camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
    camera.position.z = 300;

            // Add the controls
            controls = new THREE.OrbitControls( camera );
    controls.addEventListener( 'change', render );
    // scene

    scene = new THREE.Scene();

        var ambient = new THREE.AmbientLight( 0x101030 );
    scene.add( ambient );

    var directionalLight = new THREE.DirectionalLight( 0xffeedd );
    directionalLight.position.set( 0, 0, 1 ).normalize();
    scene.add( directionalLight );

    // model

    var loader = new THREE.OBJMTLLoader();
    loader.load( './three/obj/male02/male02.obj', './three/obj/male02/male02_dds.mtl', function ( object ) {
        object.position.y = - 80;
        scene.add( object );
    } );
    //

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( width, height );
    container.appendChild( renderer.domElement );
    //

    window.addEventListener( 'resize', onWindowResize, false );

}

    function onWindowResize() {
           windowHalfX = width / 2;
    windowHalfY = height / 2;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setSize( width, height );
    render();
}

function animate() {
        requestAnimationFrame( animate );
    controls.update();

}

function render() {
          // camera.lookAt( scene.position );
        renderer.render( scene, camera );
    stats.update();

}
  }

`

and in my HTML body code, I have:

<canvas style="border: dashed 1px black;margin-left: 25%;" id="mon_canvas" width="500" height="500"> 
         Sorry, no Webgl for you, IE user :c.
      </canvas>

I'm stumped on what the issue might be.

Answer №1

Instead of relying on canvas tags, consider utilizing div elements instead. Personally, I've had trouble inserting three.js objects directly into a canvas. Since the library places a canvas within a div anyway, I find it easier to skip using canvas tags altogether in my three.js projects.

<div style="border: dashed 1px black;margin-left: 25%;" id="mon_canvas" width="500" height="500"> Unfortunately, IE users won't be able to experience Webgl :c. </div>

Furthermore, for those using Chrome, it's advisable to utilize developer tools to verify that the obj and any associated images are loading from the correct location. Depending on how the obj file was exported, the MTL file might be referencing absolute file paths rather than relative ones.

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

Efficient arrow function usage in jQuery map functionality

Looking to implement an arrow function in jQuery's map function. However, after trying the following code snippet, titlesText ends up being the correct length but with empty strings: let titles = $(panelBody).find('h4'); let titlesText = $(t ...

Execute a PHP function using JavaScript/jQuery with AJAX requests

Hello everyone, I am reaching out for assistance with AJAX as I am still quite new to it. Despite the abundance of examples available, I find it challenging to grasp the concept. Specifically, I need help with my validation of a contact form using JavaScri ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

What is the optimal method for assigning a value to a specific key within a JavaScript JSON object?

Below is the information stored in a file called "fokontanys.json": { "vzdveg643": { "lldistrict":"Ambilobe", "id_province": 7, "id": null }, "vzvsdv5327": { "lldistrict ...

Best practices for effectively managing errors within JSON web tokens

I am a novice attempting to manage JWT verification. Within the function below, my goal is for the system to generate a new access token based on the refresh token if the user's access token has expired. import { asyncHandler } from "../utils/asy ...

Long Polling results in the call stack size being exceeded to the maximum limit

I am working on a long polling function that needs to be triggered at a specific time, and then continue as long as the gallery has the updating class. The gallery is represented by $("... "). function pollGallery(gallery){ if (gallery.hasClass("upda ...

Guide to counting the number of image tags within a parent div and selectively removing them starting from a specific position

My dynamic image tag <img> is generated inside a div from the database using fetching. Here is how my HTML looks: <div class='forimgbox'> <p class='palheading'>Pals</p> <img src='userpic/2232323.p ...

In a JavaScript project, encountering an error when using FB.logout that states "The expression is undefined and not a function."

Seeking to integrate Login with FB into my react website. FB.init({ appId : app_id, cookie : true, xfbml : true, version : 'v5.0' }); Followed by FB.getLoginStatus(({status}) => { if (status === 'conn ...

Updating Element Value in Python Using JS and Selenium

Hello, everyone. I'm new to coding and seeking some help regarding a problem I encountered with using 2captcha for my Python web scraping automation. Upon running the script, I receive the captcha token from 2captcha as instructed in their API documen ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

(React) Error: Unable to access property 'this' as it is set to undefined while trying to utilize refs

When using a ref in React to refer to an input field, I encountered an error: "Uncaught TypeError: Cannot read property 'this' of undefined". Despite having defined the ref, React seems unable to locate it in my code. What could be causing this i ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

Using Node JS as both an HTTP server and a TCP socket client simultaneously

Currently, I am developing a Node.js application to act as an HTTP server communicating with a TCP socket server. The code snippet for this setup is displayed below: var http = require('http'); var net = require('net'); var url = requi ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

Flow - secure actions to ensure type safety

Currently implementing flow and looking to enhance the type safety of my reducers. I stumbled upon a helpful comment proposing a solution that seems compatible with my existing codebase: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574 I ...

Tips for Resolving React.js Issues with setInterval

Is there a way to adjust setInterval in React so that it doesn't count faster than it should at the beginning of my program? Currently, 'var i' is being increased by 2 every second. How can I modify my code to resolve this issue? import Reac ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...