I’m creating a star animation using threejs. i want to change background color or screen how can i change it.
React.useEffect(() => {
init();
addSphere();
render();
}, []);
function init() {
//camera
camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
1000
);
camera.position.z = 5;
//scene
scene = new THREE.Scene();
//renderer
renderer = new THREE.WebGLRenderer();
//set the size of the renderer
renderer.setSize(window.innerWidth, window.innerHeight);
//add the renderer to the html document body
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", onWindowResize, false);
}
function addSphere() {
// The loop will move from z position of -1000 to z position 1000, adding a random particle at each position.
for (var z = -1000; z < 1000; z += 6) {
// Make a sphere (exactly the same as before).
const random = +(Math.random() * 10).toFixed(0);
let colorValue = null;
switch (random) {
case 0:
case 1:
case 2:
case 3:
colorValue = 0x8cde0d;
break;
case 4:
case 5:
case 6:
colorValue = 0x00bfff;
break;
case 7:
case 8:
case 9:
colorValue = 0x8855f3;
break;
default:
colorValue = 0x8cde0d;
break;
}
var geometry = new THREE.SphereGeometry(0.5, 32, 32);
let material = new THREE.MeshBasicMaterial({
color: colorValue,
});
var sphere = new THREE.Mesh(geometry, material);
var sphere1 = new THREE.Mesh(geometry, material);
// This time we give the sphere random x and y positions between -500 and 500
sphere.position.x = Math.random() * 1000 - 500;
sphere.position.y = Math.random() * 1000 - 500;
sphere1.position.x = Math.random() * 1000 - 500;
sphere1.position.y = Math.random() * 1000 - 500;
// Then set the z position to where it is in the loop (distance of camera)
sphere.position.z = z;
sphere1.position.z = z;
// scale it up a bit
sphere.scale.x = sphere.scale.y = 2;
sphere1.scale.x = sphere1.scale.y = 2;
//add the sphere to the scene
scene.add(sphere);
scene.add(sphere1);
//finally push it to the stars array
stars.push(sphere);
stars.push(sphere1);
console.log("length", stars.length);
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animateStars() {
// loop through each star
for (var i = 0; i < stars.length; i++) {
star = stars[i];
// and move it forward dependent on the mouseY position.
star.position.z += i / 30;
// if the particle is too close move it to the back
if (star.position.z > 1000) star.position.z -= 2000;
}
}