all-threads-bot

Frontender`s Spectre

How to Create a 360º Image Viewer for Panorama Images using JavaScript in Minutes

3 мая 2023 г., 05:45
How to Create a 360º Image Viewer for Panorama Images using JavaScript in Minutes | Tushar Kanjariya
Created with Coolors a Great Gradient and Color Generator

👉 Setting up the HTML file

<!DOCTYPE html><html>  <head>    <title>Panorama Viewer</title>    <style>      body {        margin: 0;        overflow: hidden;      }      #panorama-container {        width: 100%;        height: 100%;      }    </style>  </head>  <body>    <div id="panorama-container"></div>    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>    <script src="script.js"></script>  </body></html>

👉 Loading the panorama image

// Define variableslet camera, scene, renderer, controls;// Initialize the sceneinit();function init() {  // Create a new camera object  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);  // Set the camera position  camera.position.set(0, 0, 0.1);  // Create a new scene object  scene = new THREE.Scene();  // Load the panorama image  const loader = new THREE.TextureLoader();  const texture = loader.load('panorama.jpg');  // Set the texture wrapping and flipping options  texture.wrapS = THREE.RepeatWrapping;  texture.repeat.x = -1;  // Create a new sphere geometry to hold the panorama image  const geometry = new THREE.SphereGeometry(500, 60, 40);  // Flip the geometry inside out so that the image is displayed on the inside of the sphere  geometry.scale(-1, 1, 1);  // Create a new material with the loaded texture  const material = new THREE.MeshBasicMaterial({    map: texture  });  // Create a new mesh with the geometry and material  const mesh = new THREE.Mesh(geometry, material);  // Add the mesh to the scene  scene.add(mesh);}

👉 Enabling mouse drag controls

// Create a new WebGL renderer objectrenderer = new THREE.WebGLRenderer();// Set the renderer size to the window sizerenderer.setSize(window.innerWidth, window.innerHeight);// Append the renderer to the document bodydocument.getElementById("panorama-container").appendChild(renderer.domElement);// Create a new OrbitControls object to enable mouse drag controlscontrols = new THREE.OrbitControls(camera, renderer.domElement);// Disable vertical movement of the cameracontrols.enableZoom = false;controls.enablePan = false;// Set the controls to rotate around the panorama imagecontrols.rotateSpeed = -0.25;

👉 Rendering the scene

// Set the render looprenderer.setAnimationLoop(() => {    // Update the OrbitControls    controls.update();    // Render the scene with the camera and renderer    renderer.render(scene, camera);});

👉 Conclusion

Level Up Coding