Write an website using 3js and very advanced code
- User
Write an website using 3js and very advanced code
- Assistant
Certainly! Below is an example of a sophisticated website utilizing Three.js to create an interactive 3D scene. This example includes advanced features such as custom shaders, realistic lighting, environment mapping, post-processing effects, and responsive interactions.
Features Implemented:
- Scene Setup: Initializes the Three.js scene, camera, and renderer.
- Advanced Lighting: Uses multiple light sources including ambient, directional, and point lights with shadows.
- Environment Mapping: Applies a cubemap for realistic reflections and background.
- Custom Shader Material: Implements a custom shader for dynamic material effects.
- Model Loading: Loads a GLTF model with textures and animations.
- Post-Processing: Adds effects like bloom and depth of field using
EffectComposer. - Controls: Integrates
OrbitControlsfor user interaction anddat.GUIfor real-time parameter tweaking. - Responsive Design: Ensures the canvas resizes with the browser window.
- Performance Optimization: Includes techniques like frustum culling and efficient texture management.
Complete HTML and JavaScript Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Advanced Three.js Website</title> <style> body { margin: 0; overflow: hidden; } #gui { position: absolute; top: 0; right: 0; } </style> </head> <body> <script type="module"> // Import Three.js and necessary modules import * as THREE from 'https://unpkg.com/three@0.152.2/build/three.module.js'; import { OrbitControls } from 'https://unpkg.com/three@0.152.2/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'https://unpkg.com/three@0.152.2/examples/jsm/loaders/GLTFLoader.js'; import { EffectComposer } from 'https://unpkg.com/three@0.152.2/examples/jsm/postprocessing/EffectComposer.js'; import { RenderPass } from 'https://unpkg.com/three@0.152.2/examples/jsm/postprocessing/RenderPass.js'; import { UnrealBloomPass } from 'https://unpkg.com/three@0.152.2/examples/jsm/postprocessing/UnrealBloomPass.js'; import { ShaderPass } from 'https://unpkg.com/three@0.152.2/examples/jsm/postprocessing/ShaderPass.js'; import { FXAAShader } from 'https://unpkg.com/three@0.152.2/examples/jsm/shaders/FXAAShader.js'; import { GUI } from 'https://unpkg.com/dat.gui@0.7.9/build/dat.gui.module.js'; // Scene, Camera, Renderer const scene = new THREE.Scene(); // Load Environment Map const cubeTextureLoader = new THREE.CubeTextureLoader(); const environmentMap = cubeTextureLoader.load([ 'https://threejs.org/examples/textures/cube/Bridge2/posx.jpg', 'https://threejs.org/examples/textures/cube/Bridge2/negx.jpg', 'https://threejs.org/examples/textures/cube/Bridge2/posy.jpg', 'https://threejs.org/examples/textures/cube/Bridge2/negy.jpg', 'https://threejs.org/examples/textures/cube/Bridge2/posz.jpg', 'https://threejs.org/examples/textures/cube/Bridge2/negz.jpg', ]); scene.background = environmentMap; scene.environment = environmentMap; const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set(0, 2, 5); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.outputEncoding = THREE.sRGBEncoding; renderer.shadowMap.enabled = true; document.body.appendChild(renderer.domElement); // Controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // Lights const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 1); directionalLight.position.set(5, 10, 7.5); directionalLight.castShadow = true; directionalLight.shadow.mapSize.set(1024, 1024); scene.add(directionalLight); const pointLight = new THREE.PointLight(0xff0000, 1, 100); pointLight.position.set(-5, 5, -5); scene.add(pointLight); // Ground const ground = new THREE.Mesh( new THREE.PlaneGeometry(100, 100), new THREE.MeshStandardMaterial({ color: 0x808080, depthWrite: false }) ); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground); // Custom Shader Material const vertexShader = ` varying vec3 vNormal; varying vec3 vPosition; void main() { vNormal = normalize(normalMatrix * normal); vPosition = (modelViewMatrix * vec4(position, 1.0)).xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `; const fragmentShader = ` uniform vec3 color; uniform float time; varying vec3 vNormal; varying vec3 vPosition; void main() { float brightness = dot(vNormal, vec3(0.0, 1.0, 0.0)) * 0.5 + 0.5; gl_FragColor = vec4(color * brightness, 1.0); } `; const shaderMaterial = new THREE.ShaderMaterial({ vertexShader, fragmentShader, uniforms: { color: { value: new THREE.Color(0x00ff00) }, time: { value: 0.0 }, }, side: THREE.DoubleSide, lights: false, }); // Geometry with Shader Material const customGeometry = new THREE.TorusKnotGeometry(1, 0.4, 128, 32); const customMesh = new THREE.Mesh(customGeometry, shaderMaterial); customMesh.position.set(0, 1, 0); customMesh.castShadow = true; scene.add(customMesh); // Load GLTF Model const gltfLoader = new GLTFLoader(); gltfLoader.load( 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', (gltf) => { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; child.material.envMapIntensity = 1.5; } }); model.scale.set(2, 2, 2); model.position.set(2, 0, 0); scene.add(model); }, undefined, (error) => { console.error('An error happened while loading the GLTF model:', error); } ); // Post-Processing const composer = new EffectComposer(renderer); const renderPass = new RenderPass(scene, camera); composer.addPass(renderPass); const bloomPass = new UnrealBloomPass( new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, // strength 0.4, // radius 0.85 // threshold ); composer.addPass(bloomPass); const fxaaPass = new ShaderPass(FXAAShader); fxaaPass.uniforms['resolution'].value.set( 1 / window.innerWidth, 1 / window.innerHeight ); composer.addPass(fxaaPass); // GUI const gui = new GUI(); const bloomFolder = gui.addFolder('Bloom'); bloomFolder.add(bloomPass, 'strength', 0, 3).name('Strength'); bloomFolder.add(bloomPass, 'radius', 0, 1).name('Radius'); bloomFolder.add(bloomPass, 'threshold', 0, 1).name('Threshold'); bloomFolder.open(); const materialFolder = gui.addFolder('Custom Material'); materialFolder.addColor({ color: '#00ff00' }, 'color') .onChange((value) => shaderMaterial.uniforms.color.value.set(value)) .name('Color'); materialFolder.open(); // Animation Loop const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const delta = clock.getDelta(); shaderMaterial.uniforms.time.value += delta; customMesh.rotation.y += delta * 0.5; controls.update(); composer.render(); } animate(); // Handle Window Resize window.addEventListener('resize', () => { const width = window.innerWidth; const height = window.innerHeight; camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); composer.setSize(width, height); fxaaPass.uniforms['resolution'].value.set(1 / width, 1 / height); }); </script> </body> </html>Explanation of Key Components:
-
Module Imports: The script uses ES6 modules to import Three.js core and additional modules like
OrbitControls,GLTFLoader, and post-processing passes from a CDN. -
Environment Mapping: A cubemap is loaded to create realistic reflections on materials that support environment mapping. This also serves as the scene's background.
-
Lighting:
- AmbientLight provides a base illumination.
- DirectionalLight simulates sunlight with shadows.
- PointLight adds a localized light source with a distinctive color.
-
Custom Shader Material:
- Vertex Shader calculates normals and positions for lighting effects.
- Fragment Shader uses these to create dynamic coloring based on normals.
- Uniforms allow dynamic adjustments of color and time for animations.
-
GLTF Model Loading: Demonstrates how to load and integrate external 3D models into the scene with appropriate scaling and positioning.
-
Post-Processing:
- EffectComposer chains multiple post-processing effects.
- UnrealBloomPass adds a bloom effect for highlights.
- FXAAShader implements Fast Approximate Anti-Aliasing to smooth out edges.
-
GUI Controls:
dat.GUIprovides an interface for real-time tweaking of bloom parameters and custom material color. -
Responsive Design: The renderer and composer adjust their sizes dynamically when the browser window is resized, maintaining aspect ratios and effect resolutions.
-
Animation Loop: Continuously updates the scene, including rotating the custom mesh and rendering post-processing effects.
Usage:
- Environment Setup: Ensure you have a stable internet connection as the script imports resources from CDNs.
- Customization: Modify shader code, lighting parameters, or add more models as needed to fit your project's requirements.
- Deployment: Save the code in an
.htmlfile and open it in a modern web browser to view the interactive 3D scene.
This example serves as a robust foundation for building complex 3D web applications using Three.js. You can expand upon it by adding more interactive elements, integrating physics engines, or optimizing for performance based on your specific use case.