76 lines
2.1 KiB
JavaScript

import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
const scene = new THREE.Scene();
scene.background = new THREE.Color("white");
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry(1.5, 100, 100);
const loader = new THREE.TextureLoader();
const textures = {
earth: loader.load('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQZVsp7bSmsdGhM1GouOYgZ6l06Za__Z1ZY8A&s'),
moon: loader.load('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROh1go667NHsMdzLyvI-0tt9Mn0eugRp0xhQ&s'),
sun: loader.load('https://upload.wikimedia.org/wikipedia/commons/a/a4/Solarsystemscope_texture_8k_sun.jpg')
};
const material = new THREE.MeshStandardMaterial({
map: textures.earth,
roughness: 0.6
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.set(5, 5, 5);
scene.add(pointLight);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const buttons = document.querySelectorAll("button");
buttons.forEach((btn) => {
btn.addEventListener("click", () => {
const variant = btn.getAttribute("data-variant");
mesh.material.map = textures[variant];
mesh.material.needsUpdate = true;
buttons.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
});
});
function animate() {
requestAnimationFrame(animate);
controls.update();
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});