If I were to utilize my own Threejs canvas,Rephrased

Currently, I'm facing an issue while trying to showcase a globe using Three.js. Everything works perfectly until I attempt to use my own canvas. It seems that when I place my canvas before the JavaScript file in the HTML structure, it doesn't display correctly and instead shows a blank canvas. Below is the code snippet initializing the canvas:

    renderer = new THREE.WebGLRenderer({ antialias: true, canvas: myCanvas });
    renderer.setSize(width, height);
    console.log(renderer.domElement)

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera();
    camera.aspect = width/height;
    camera.updateProjectionMatrix();

    scene.add(new THREE.AmbientLight(0xbbbbbb));
    scene.add(new THREE.DirectionalLight(0xffffff, 0.6));

    camera.position.z = 300;
    camera.position.x = 0;
    camera.position.y = 0;

    scene.add(camera);

    scene.fog = new THREE.Fog(0x545ef3, 400, 2000);

    // Add camera controls
    controls = new THREE.TrackballControls(camera, renderer.domElement);
    controls.minDistance = 101;
    controls.rotateSpeed = 1;
    controls.zoomSpeed = 0.3;

    window.addEventListener("resize", onWindowResize, false);
    window.addEventListener('click', onClick, false); 
    //document.body.appendChild(renderer.domElement);

If I comment out the last line, although the canvas is still there in the document object model (DOM), it remains empty. If I uncomment it, the canvas appears at the end of the body as expected, but it displays as a black canvas. Does anyone have insights into why this behavior is occurring?

Answer №1

When it comes to creating a renderer in the context of canvas, there are generally three methods you can use.

  1. If you don't include the canvas parameter, the renderer will generate an internal canvas. You can access it using WebGLRenderer.domElement and must assign it to the DOM, typically with

    document.body.appendChild(renderer.domElement);
    .

  2. You may already have a canvas in your DOM which you can select via JavaScript like

    document.getElementById( 'myCanvas' );
    . In this scenario, you need to specify it in the constructor as shown in your sample code.

  3. The third option is to create a canvas inline using something like createElementNS( 'canvas' ). Here, you must define it during renderer creation and also add it to the DOM.

Based on the information provided, it seems you are using option 2. Therefore, the line

document.body.appendChild(renderer.domElement);
is not required because the canvas is already part of the DOM.

I recommend running your code when the DOM is fully loaded. Attach an event listener to the DOMContentLoaded event and run your three.js code within it.

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

Trouble arises when attempting to showcase document fields in MongoDB

As a beginner in programming, I am putting in my best effort to figure things out on my own. However, I seem to be stuck without any guidance. I am attempting to display all products from the mongoDB based on their brand. While I have successfully set up a ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

I'm looking for a solution to correct the array output from my function in node

I have a function that is currently functioning, but I am in need of proper array sorting. First, I will display my code, followed by the current output and then the desired output. Can someone help me edit my entire code and output? var app = require(&a ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Experiencing an error message of "undefined" when attempting to retrieve a value from outside

While working with Node.js, I utilized a request to fetch some data from an API. However, when I attempted to access these values outside of the function braces, they returned undefined. var tab_det; request.post({url:'https://ludochallenge.com/i ...

Tips for speeding up the transition time of a floating header while scrolling

On this website , I am interested in adjusting the timing of the transition effect on the header background when hovering on scroll. Currently, the transition begins between two scrolls, but I would like it to start immediately after the first scroll. Can ...

Tips for adjusting the height of a textbox to fit predetermined text on variously sized pages

While revisiting some of my older code, I came across a method that statically resizes the height of a textbox control during runtime based on the client's screen width. The approach involved hardcoding values for specific screen resolutions, such as ...

The alpha channel in THREE.js GLTFLoader is not displaying transparency and instead showing a white background

I imported a model created in Blender: https://i.sstatic.net/SF0D2.png The texture of the model is partially transparent, achieved by converting the white background to alpha using nodes: https://i.sstatic.net/lSZ6w.png To make this work correctly, I en ...

AJAX, JQuery, JQuery UI, CSS, and custom JavaScript are experiencing loading issues

Can anyone explain why my AJAX requests only work when I remove //code.jquery.com/jquery-1.9.1.js from my site, but then I can't access the JQuery UI datePicker? <head> <link rel="stylesheet" type="text/css" href="CSS/custom.css"> < ...

Tips for organizing ng-repeat information according to a condition of true or false

Apologies if this question has already been addressed, but I have not been able to find a solution. I am attempting to organize an ng-repeat based on the selection of radio buttons, but I am struggling with hiding and showing items within the ng-repeat. ...

steps for integrating react-pannellum library into react/ionic

Trying to integrate a 3D panorama view into my React Ionic app, but encountering an error while attempting to install using either of the following commands: npm install --save react-pannellum npm install --save pannellum > npm WARN config global `-- ...

Error encountered: jquery form validation fails to register changes

I am currently developing a calculator-like code where users will submit a form multiple times, and I need to save the result of calculations only if there are changes in the form. For instance, when a user clicks the "Calculate" button for the first time, ...

Utilize AngularJS to compare and eliminate duplicate elements between two lists

Two lists are causing me trouble: List1 = ['option1','option2','option3','option4','option5','option6','option7']; List2 = ['option3', 'option4', 'option7&ap ...

The challenge of maintaining consistency in Vue 3 when it comes to communication between

Context In my Vue 3 application, there is a HomeView component that contains the following template structure: <InputsComponent></InputsComponent> <CheckboxesComponent></CheckboxesComponent> <Toolbar></Toolbar> T ...

Arrange images with haphazard placement

Can someone guide me on creating a block of images when working with an array of random items? https://i.sstatic.net/qEcQy.png ...

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

Utilize FileHandle throughout various versions of Node.js

Is it possible to import the FileHandle module successfully across different versions of Node.js? For example, in Node.js v14 and v16, the following code functions properly: import { FileHandle } from "fs/promises"; However, in Node.js v12, thi ...

What is the best way to update a specific section of my website by modifying the URL while keeping the menus fixed and the site functioning smoothly?

I am in desperate need of assistance as I search for a solution. Currently, I am working on a project involving music within a web browser or application. My goal is to utilize HTML, PHP, JS, and CSS to create this project. If I start with a website, I p ...

Showing user avatar icon with automatically generated name initials

I am looking for a way to generate an avatar icon based on a person's name. The icon should consist of the first letters of each word in the name. For example, if the name is John Abraham, the icon should display 'JA'. I plan to use this av ...

Troubleshooting: Issue with Bootstrap 4 navbar toggle button functionality

Is it possible to manually control the opening and hiding of the navbar when the toggle button is clicked in bootstrap 4? Currently, my navbar automatically opens and closes when clicking the toggle button. Any suggestions on how to modify this behavior wo ...