Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing three.js background to transparent or other color

I've been trying to change what seems to be the default background color of my canvas from black to transparent / any other color - but no luck.

My HTML:

<canvas id="canvasColor">

My CSS:

<style type="text/css">
#canvasColor {
 z-index: 998;
opacity:1;
background: red;
}
</style>

As you can see in the following online example I have some animation appended to the canvas, so cant just do a opacity: 0; on the id.

Live preview: http://devsgs.com/preview/test/particle/

Any ideas how to overwrite the default black?

like image 378
user1231561 Avatar asked Oct 16 '22 09:10

user1231561


People also ask

How do you make a background transparent in 3 js?

If you want a transparent background in three. js, you need pass in the alpha parameter to the WebGLRenderer constructor. var renderer = new THREE. WebGLRenderer( { alpha: true } );

How do you change the background color in JavaScript?

We can change the background color using the backgroundColor property in JavaScript. To use this property, you need to get the element whose background color you want to change, and then you can use the backgroundColor property to set the background color.

Which property is used to change the background color in JavaScript?

The background-color CSS property sets the background color of an element.


2 Answers

I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:

renderer.setClearColorHex( 0x000000, 1 );

in your threejs init function. Change it to:

renderer.setClearColorHex( 0xffffff, 1 );

Update: Thanks to HdN8 for the updated solution:

renderer.setClearColor( 0xffffff, 0);

Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor() function:

var renderer = new THREE.WebGLRenderer({ alpha: true });

Update #3: Mr.doob points out that since r78 you can alternatively use the code below to set your scene's background colour:

var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );
like image 308
Joe Avatar answered Oct 17 '22 23:10

Joe


A full answer: (Tested with r71)

To set a background color use:

renderer.setClearColor( 0xffffff ); // white background - replace ffffff with any hex color

If you want a transparent background you will have to enable alpha in your renderer first:

renderer = new THREE.WebGLRenderer( { alpha: true } ); // init like this
renderer.setClearColor( 0xffffff, 0 ); // second param is opacity, 0 => transparent

View the docs for more info.

like image 30
Yotam Omer Avatar answered Oct 17 '22 23:10

Yotam Omer