Untitled
unknown
plain_text
a year ago
2.7 kB
9
Indexable
// Retrieve the canvas element for rendering
const canvas = document.getElementById('pianoCanvas');
// Initialize the scene
const scene = new THREE.Scene();
// Set up the camera with perspective projection
const camera = new THREE.PerspectiveCamera(
75, // Field of view
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
// Create the WebGL renderer and attach it to the canvas
const renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Adjust camera position for a better view
camera.position.z = 5;
// Function to create a basic 3D piano model
function createPiano() {
// Piano base
const baseGeometry = new THREE.BoxGeometry(4, 0.5, 2);
const baseMaterial = new THREE.MeshStandardMaterial({ color: '#2d2d2d' });
const base = new THREE.Mesh(baseGeometry, baseMaterial);
base.position.y = -0.5; // Position slightly below the center
scene.add(base);
// Piano keys (white keys)
for (let i = 0; i < 12; i++) {
const keyGeometry = new THREE.BoxGeometry(0.3, 0.1, 1);
const keyMaterial = new THREE.MeshStandardMaterial({ color: '#ffffff' });
const key = new THREE.Mesh(keyGeometry, keyMaterial);
key.position.set(-1.65 + i * 0.35, 0, 0.5);
scene.add(key);
}
// Piano keys (black keys)
const blackKeyPositions = [0, 1, 3, 4, 5, 7, 8, 10];
blackKeyPositions.forEach((pos) => {
const keyGeometry = new THREE.BoxGeometry(0.2, 0.1, 0.6);
const keyMaterial = new THREE.MeshStandardMaterial({ color: '#000000' });
const key = new THREE.Mesh(keyGeometry, keyMaterial);
key.position.set(-1.475 + pos * 0.35, 0.1, 0.3);
scene.add(key);
});
}
// Add lights to illuminate the scene
const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); // Strong directional light
directionalLight.position.set(10, 10, 10);
scene.add(directionalLight);
// Call the function to add the piano to the scene
createPiano();
// Render loop to continuously update the scene
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
// Resize handler for responsiveness
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Start animation
animate();
Editor is loading...
Leave a Comment