Background color set to black in Three.js canvas

I tried creating a basic scene with three.js but I'm puzzled as to why the canvas background is showing up completely black.

<html>
<head>
    <title>My first Three.js app</title>
    <style>
        body { margin: 0; }
        canvas { width: 100%; height: 100%;background-color: white; }
    </style>
</head>
<body>
    <script src="Stereos/threejs/three.js"></script>
    <script>
        var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
    </script>
  </body>
</html>

EDIT:

Check out the code at felpone.netsons.org

Answer №1

The background color of the canvas is set dynamically through the use of

renderer.setClearColor (0xff0000, 1);

Answer №2

To customize the background color using CSS, ensure that the "alpha" property of your WebGLRenderer is set to "true." This will allow you to have control over the background color.

As an example, I included the alpha option and set it to true in the renderer. Additionally, I specified the background-color property in the body style as well.

<html>
    <head>
        <title>My first Three.js app</title>
        <style>
            body { margin: 0; background-color: white; }
            canvas { width: 100%; height: 100%; background-color: white; }
        </style>
    </head>
    <body>
    <script src="Stereos/threejs/three.js"></script>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

        var renderer = new THREE.WebGLRenderer( {alpha: true} );
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
    </script>
    </body>
</html>

Answer №3

It is recommended to add the background directly to the scene, whether it's a texture or a THREE.Color!

Starting from r78 versions, you can set the background color of your scene using the code snippet below:

var scene = new THREE.Scene();
scene.background = new THREE.Color( 0x000000 );

Check out the documentation for more details:

  • Scene.background

Answer №4

You set up a scene, camera, and renderer, but don't forget the essential steps: giving something to render and actually rendering it.

Once you've finished your code, make sure to include:

var cube = new THREE.Mesh( 
    new THREE.CubeGeometry(1, 1, 1), 
    new THREE.MeshNormalMaterial() 
);
scene.add(cube);

camera.position.set(2, 2, 2);
camera.lookAt(cube.position);

renderer.render(scene, camera);

This will generate a cube at the origin (0,0,0) with dimensions of 1 unit; position the camera near the cube and focused on it; then instruct the renderer to display the cube.

Answer №5

To keep up with the latest version of ThreeJS (2019) -

Once you create your scene by using:

scene = new THREE.Scene();

You can then modify the "background" property of this instance and assign a hex color value like so:

scene.background = new THREE.Color(0xf5f5f5);

Answer №6

In my opinion, @Jaume Sanchez provides the most accurate response. While the other answers contain relevant information, they may not fully address the specific concerns of someone new to threeJS. The var renderer variable simply points to your render target and does not actually draw anything. Additionally, without a camera in your scene, there is nothing for the renderer to display. For more comprehensive guidance on setting up a scene in threeJS, I recommend checking out this tutorial on creating a scene.

Answer №7

You mentioned that you have experimented with a simple scene, but encountered a black screen. Upon reviewing your code, I noticed a crucial error.

It appears that you forgot to call the render method.

renderer.render(scene, camera);

In addition, it seems like you haven't added any Geometry (Mesh) to your threejs scene, which is fundamental.

This could be causing the issue of the black screen.

If your objective is to transform the black screen into a white one,

then you should set

 scene.background = new THREE.Color(0xffffff);

Answer №8

If you encounter an issue where:

renderer.setClearColor(0xff0000, 1);

is not functioning properly, you can try the following solution:

const renderer = new THREE.WebGLRenderer();
renderer.domElement.className = "domElement";

Add a selector in your CSS file:

.domElement {
  background-color: red; /* choose any color */
}

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

Unlock the modal after choosing an image file

Whenever I click on the upload button, my modal opens with the explorer window. I am looking to have the modal open after selecting an Image file. Below is my HTML and JQuery code: $uploadCrop = $('#upload-demo').croppie({ enableExif: true, ...

Ways to display information using a show/close button in React

I am currently immersed in the learning process of React. My goal is to display information about different countries using a toggleable button. However, I have encountered some obstacles along the way. There's an input field that triggers upon enteri ...

How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation. app.get("/male",function (req,res) { Record.aggregate([ { $match: {"gender": "male"} }, { $group:{ _i ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

Generating dynamic divs in parallel

Despite encountering numerous posts related to the issue at hand, none of them have solved my specific problem. I am aiming for 3 divs to display in each row, but the current code is causing each div to show up on a new line vertically: JQuery ...

Encountered an error while trying to import the module: Unable to locate module 'react-redux'

I keep encountering the following errors and I'm unsure of where I'm making a mistake. Any assistance would be greatly appreciated. I've made changes to my webpack configuration and updated the react-hot-webpack loader, but the errors persis ...

What is the best way to pass parameters in jQuery using .on()?

Hello there, I have a slight dilemma :) Could you please advise me on how to pass a parameter to an external JavaScript function using the .on method? Here is the code snippet: <script> var attachedPo = 0; $this.ready(function(){ $ ...

What is the quickest way to display data immediately after submitting a form using ajax?

Is there a way to display data instantly after submitting a form via AJAX and saving it through a controller function? I want to be able to view the saved data on the same page without having to refresh it: <span class=" store_comment_like " data-com ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

Modify input attribute by selecting a label

What I'm looking for: I am trying to add a checked status to the input field when a label is clicked. However, when I attempted this, I received two alerts displaying "true." This behavior is incorrect, and upon inspection in Firebug, the input fiel ...

Firebase's push() method compared to Angularfire's $save() operation

When comparing angularfire .$save() to firebase .push(), what are the differences? I understand that push() generates a unique key when data is stored, but I'm having trouble replicating this behavior with angularfire. Should I stick to using .push() ...

"Implementing a Redux structure to enhance audio player functionality and effectively manage error

Imagine I am in the process of developing an audio player that includes a control panel for users to pause/play the currently selected track, along with the actual audio players. This involves actions such as pausing/playing the track, with the audio playe ...

Trying to modify a read-only property in Ionic 2 and Angular 2 is causing an error

Utilizing the Ionic refresh API allows for pulling and refreshing a page with updates to be accomplished. Within an Angular2 page, I am trying to use the refresh method to clear existing rows and then add new rows using the .push() method. However, when I ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Is the value incorrect when using angular's ng-repeat?

Currently iterating through an array nested within an array of objects like this: <div ng-repeat="benefit in oe.oeBenefits"> <div class="oeInfo" style="clear: both;"> <div class="col-md-2 oeCol"> <img style="he ...

How can I utilize customToJSON in Sails 1.0 within an Action2 function?

Currently, I am facing an issue with my user model that requires the implementation of a customToJSON method to remove the password field from the returned JSON object. Everything works fine when I include "responseType" in the "exits" with a value of "jso ...

What steps should I take to resolve the error: Uncaught SyntaxError: expected expression, received '<'?

I'm facing an issue with my code. It works perfectly on my computer, but when I move it to the server, I encounter the following error. Error: Uncaught SyntaxError: expected expression, got '<' Here is the code snippet causing the prob ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

The functionality of scrolling in Angular Material tabs is not functioning properly

I have encountered a challenge while working with angularjs material design. The md-scroll functionality is not working as expected for scrolling up and down, even though it works fine for left and right scrolling. In a tab with a table view, the vertical ...