Open mysterion opened 5 months ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cube to Sphere Transformation</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create a cube geometry with subdivisions
const geometry = new THREE.BoxGeometry(1, 1, 1, 10, 10, 10); // The 4th, 5th, and 6th arguments add subdivisions
// Access the position attribute of the geometry
const positionAttribute = geometry.attributes.position;
const sphereRadius = 1.5; // Set the radius of the sphere
// Loop through each vertex and project onto the sphere
for (let i = 0; i < positionAttribute.count; i++) {
const x = positionAttribute.getX(i);
const y = positionAttribute.getY(i);
const z = positionAttribute.getZ(i);
// Calculate the length (distance from origin)
const length = Math.sqrt(x * x + y * y + z * z);
// Normalize and scale to sphere radius
const newX = (x / length) * sphereRadius;
const newY = (y / length) * sphereRadius;
const newZ = (z / length) * sphereRadius;
// Set the new vertex positions
positionAttribute.setXYZ(i, newX, newY, newZ);
}
// Update the geometry after modification
positionAttribute.needsUpdate = true;
// Create a basic material and mesh
const material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
// Render loop
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
Specs: https://gist.github.com/gtk2k/2aa7aa1a1c6beeb9f9829c7be335a08f