Display a Three.js scene on a canvas

I've been attempting to display the image below on a canvas numerous times, but unfortunately I can't seem to get it right.
I attempted substituting

var renderer = new THREE.WebGLRenderer({antialias: true});
with
var renderer = new THREE.WebGLRenderer({ canvas: canvas });
, however instead of rendering, it just keeps loading indefinitely.

Here's the complete HTML page: https://jsfiddle.net/1k04rwsx/ (replace the obj models with something to trigger it to load)

P.S.: I'm fairly new at this, so please pardon any unconventional code.
A big thank you to anyone who can offer assistance!

Answer №1

The reason your loading screen isn't disappearing is because you were loading OBJs from relative URLs, which is not supported in jsFiddle. I replaced one URL with an official repository link and now everything is working smoothly.

/**
  * Creating a scene object with a background color
  **/

  function getScene() {
    var scene = new THREE.Scene();
    scene.background = new THREE.Color(0x111111);
    return scene;
  }

  /**
  * Setting up the camera for the scene. Camera parameters:
  *   [0] field of view: determines what's visible at any time (in degrees)
  *   [1] aspect ratio: width/height ratio of the scene
  *   [2] near clipping plane: objects closer than this are culled
  *   [3] far clipping plane: objects farther than this are culled
  **/

  function getCamera() {
    var aspectRatio = window.innerWidth / window.innerHeight;
    var camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 1000);
    camera.position.set(0, 1, -10);
    return camera;
  }

  // Light setup

  function getLight(scene) {
    var light = new THREE.PointLight(0xffffff, 1, 0);
    light.position.set(1, 5, -2);
    scene.add(light);

    const lighta = new THREE.AmbientLight( 0x404040 );
    scene.add( lighta );

    var ambientLight = new THREE.AmbientLight(0x111111);
    scene.add(ambientLight);
    return light;
  }

  // Renderer setup

  function getRenderer() {
    var renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    return renderer;
  }

  // Controls setup

  function getControls(camera, renderer) {
    var controls = new THREE.TrackballControls(camera, renderer.domElement);
    controls.zoomSpeed = 0.4;
    controls.panSpeed = 0.4;
    return controls;
  }

  // Load model

  function loadModel() {
    var loader = new THREE.OBJLoader();
    loader.load( 'https://threejs.org/examples/models/obj/tree.obj', function ( object ) {
      object.rotation.y = 1.5;
      object.scale.y = 0.7;
      object.scale.x = 0.7;
      object.scale.z = 0.7;
      scene.add( object );
      document.querySelector('h1').style.display = 'none';
    } );
  }

  // Render loop

  function render() {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
  };

  var scene = getScene();
  var camera = getCamera();
  var light = getLight(scene);
  var renderer = getRenderer();
  var controls = getControls(camera, renderer);

  loadModel();

  render();
html, body { width: 100%; height: 100%; background: #000; color: #fff; }
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100%; }
<script src='https://cdn.jsdelivr.net/npm/three@0.130.0/build/three.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/three@0.130.0/examples/js/controls/TrackballControls.js'></script>
<script src='https://cdn.jsdelivr.net/npm/three@0.130.0/examples/js/loaders/OBJLoader.js'></script>
<h1 style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"><div class="lds-dual-ring"></div></h1>

By the way, make sure not to mix classes from different releases of three.js. Stick to a single release like in the code above for consistency.

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

I am experiencing difficulties with the React-router useHistory function

Currently working on a project involving react and nodejs. Utilizing window.location.href to redirect to another page upon successful login, however, attempting to use useHistory for redirection without updating is yielding an error message: Error Uncaugh ...

Eliminate the selected item at random

I'm looking for a way to remove the randomly picked item from my namepicker so that it doesn't appear twice. const Names = [ { name: 'Name1', id: 1 }, { name: 'Name2', id: 2 }, ] btnClick = () => { let ...

Recreate body content with JQuery Mobile

I've been attempting to duplicate the entire HTML content within the tags. However, even though the appearance on screen is correct, none of the links are functioning.</p> <p>To view the fiddle, click here: [Here is a fiddle][1]</p> ...

Transform the JSON response into a map

I have a functioning code that I am looking to adjust. let table_specs = {'columns': [ {'name': 'Col1', 'width': 7, ....}, {'name': 'Col2', 'width': 8, . ...

Differences in Loading Gif Visualization Across Chrome, Safari, and Firefox

Having an issue with a loading image in Chrome, while it displays correctly in Safari and Firefox. In Chrome, I see two half-loading images instead of one whole image. Struggling to find a solution for this problem, any assistance would be greatly apprecia ...

Upon clicking the initial radio button, the jQuery array contents are not immediately displayed

Here is the HTML code that I am working with: if(isset($_POST['itemid'])) { <table class="table table-striped table-condensed table-bordered table-rounded errorcattable"> <thead> <tr> <th colspan='4'> ...

Using JavaScript, pass an array containing a list of JSON values

I am attempting to store a list of JSON Objects in an array using JavaScript. Below is the list: [{"_id":1,"json":{"age":10,"name":"carlos"}},{"_id":2,"json":{"age":10,"name":"carlos"}}] Here is the code snippet I have written: var arrayResults = ' ...

Tips for dynamically adding and removing keys from a JSON object

I am working on a code for a car rental website using jQuery mobile. I need to dynamically add and remove keys from a JSON object with true or false values. The goal is to make a selected car unavailable by changing the "available" key to either true or ...

What is the best way to invoke a method within the $http body in AngularJS

When I try to call the editopenComponentModal method in another method, I encounter the following error: angular.js:13920 TypeError: Cannot read property 'editopenComponentModal' of undefined EditCurrentJob(job) { this.$http.put(pr ...

Difficulty interpreting description and metadata within a JSON object using JavaScript

In my NODE JS code, I have a JSON object as shown below. I am attempting to retrieve the description and metadata values, but I am only getting undefined results. Are "description" and "metadata" reserved keywords in any way? If so, how should I handle an ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

The rendering of the component is experiencing issues when using react-router

function App() { return ( //Following BEM naming convention <div className="app"> <div className="app__body"> <Sidebar /> <Chat /> <Router> <Routes> ...

The issue of continuous requests in AngularJS controllers

In my controller, I have a simple function that calculates the number of answers for each question: $scope.countAnswers = function(questionid) { AnswersQueries.getAnswers(questionid, function(answers) { var answersCount = answers.length; return ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Preventing further onClick events from occurring ensures that any new onClick events will not be triggered as well. To achieve

In the process of developing a script, I've encountered a situation where the original developers may have implemented event prevention or some other mechanism to block any additional clicks on certain table td elements. Even though their click trigge ...

Exploring the possibilities of Three.JS by manipulating the world position of a child 3D object

I have a child object3D that is part of a group Object3D. While the child object's position is displayed relative to the parent object's space, I am trying to change the location of the child object within the 3D space. To do this, I first need t ...

Implementing JavaScript to import an external file easily

I found this code snippet to change text by clicking on it, but now I want to load the text from an external file text.txt instead of embedding it directly into the page. $(document).ready(function() { $("#div3").click(function() { changtext(); ...

A Javascript promise that perpetually stays in a pending state

Utilizing the rotateByDegrees function from a library called node-poweredup within a typescript project: motor.rotateByDegrees(20,10).then(function(value) {console.log("test");}, function(value) {console.log("error");}); Expecting to s ...

Guide: Transform Bootstrap 4 Inline Checkboxes into Stacked Format When Screen Size Is Altered

The new layout of checkboxes and radio buttons in Bootstrap 4 really caught my attention. However, I am looking for a way to switch between "stack" and "inline" based on the screen size. Although size tagging has been added for various elements, I haven&ap ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...