360 Image Viewer JavaScript

360 Image Viewer JavaScript
Code Snippet:Panoramic Image Viewer
Author: Bryan Jones
Published: May 5, 2024
Last Updated: May 5, 2024
Downloads: 55
License: MIT
Edit Code online: View on CodePen
Read More

This code creates a 360 image viewer using JavaScript. It allows viewing images in virtual reality. The code initializes the scene, camera, and renderer for immersive image viewing. The viewer can toggle between VR mode and regular mode for different experiences.

You can use this code on websites to enhance user experience with immersive image viewing. It’s beneficial for showcasing virtual tours, real estate properties, or product showcases. With VR support, it offers an engaging and interactive way for users to explore visual content.

How to Create 360 Image Viewer in JavaScript

1. First, load the following meta viewport assets into the head tag of your HTML document.

<meta name="viewport" content="width=device-width, initial-scale=1">

2. Now, create an HTML file and link the CSS and JavaScript files. Add a container element where the image viewer will be displayed. Also, include a button to toggle between regular and VR mode.

<!-- Click and drag the screen to move the image -->

<div id="stereo-toggle">Turn VR On</div>

3. Define basic styles to make the viewer visually appealing. You can customize these styles according to your preferences.

/**
 * @file
 * Basic styling for the program.
 */
body {
  margin: 0;
  overflow: hidden;
}

#stereo-toggle {
  background-color: rgba(0, 0, 0, 0.8);
  border: 1px solid #fff;
  border-radius: 8px;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
  left: 20px;
  padding: 10px 20px;
  position: fixed;
  top: 20px;
  z-index: 1000;
  transition: all 400ms linear;
}
#stereo-toggle:hover {
  background-color: black;
  border-color: #afa;
  color: #afa;
}

4. Load the following Three, OrbitControls, DeviceOrientationControls, jQuery, and StereoEffect Libraries before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/123879/OrbitControls.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/123879/DeviceOrientationControls.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/123879/StereoEffect.js'></script>

5. Create a JavaScript file to handle the functionality of the image viewer. This includes initializing the scene, camera, renderer, and controls. Load the image onto a sphere and enable VR mode.

/**
 * @file
 * The main scene.
 */

/**
 * Define constants.
 */
const TEXTURE_PATH = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123879/';

/**
 * Create the animation request.
 */
if (!window.requestAnimationFrame) {
  window.requestAnimationFrame = (function() {
    return window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    function (callback, element) {
      // 60 FPS
      window.setTimeout(callback, 1000 / 60);
    };
  })();
}

/**
 * Set our global variables.
 */
var camera,
    scene,
    renderer,
    controls,
    container,
    effect,
    sphere;

var stereoEffect = 0;

init();
animate(); 

/**
 * Initializer function.
 */
function init() {
  // Build the container
  container = document.createElement( 'div' );
  document.body.appendChild( container );

  // Create the scene.
  scene = new THREE.Scene();
  
  rotationPoint = new THREE.Object3D();
  rotationPoint.position.set( 0, 0, 100 );
  scene.add( rotationPoint );
  
  // Create the camera.
  camera = new THREE.PerspectiveCamera(
   45, // Angle
    window.innerWidth / window.innerHeight, // Aspect Ratio.
    1, // Near view.
    23000 // Far view.
  );

  rotationPoint.add( camera );

  // Build the renderer.
  renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
  element = renderer.domElement;
  renderer.setSize( window.innerWidth, window.innerHeight );
  renderer.shadowMap.enabled;
  container.appendChild( element );

  // Build the controls.
  controls = new THREE.OrbitControls( camera, element );
  controls.enablePan = true;
  controls.enableZoom = true; 
  controls.maxDistance =  window.innerHeight / 4;
  controls.minDistance = 1;
  controls.target.copy( new THREE.Vector3( 0, 0, -100 ) );
  
  
  // Add the VR screen effect.
  effect = new THREE.StereoEffect(renderer);
  effect.eyeSeparation = 5;
	effect.setSize( window.innerWidth, window.innerHeight );
  
  // Add the light source.
  var light = new THREE.PointLight( 0xffffff, 1, 10000, 0 );
  light.position.set( 0, 0, 0 );
  scene.add( light );
  
  // Create materials for Enceladus. 
  loader = new THREE.TextureLoader();
  loader.setCrossOrigin( 'https://s.codepen.io' );
  var texture = loader.load( TEXTURE_PATH + 'Lions.jpeg' );

  var material = new THREE.MeshPhongMaterial({
    color: "#ffffff",
    shininess: 10,
    map: texture,
    specular: "#000000",
    side: THREE.BackSide,
  });
  
  // Add the sphere container.
  var geometry = new THREE.SphereGeometry( 300, 128, 128 );
  material.side = THREE.BackSide;
  var sphere = new THREE.Mesh( geometry, material );
  sphere.position.set( 0, 0, 0 );
  sphere.rotation.y = Math.PI/1.8;
  sphere.side = THREE.BackSide;
  scene.add( sphere );
 
  window.addEventListener('resize', onWindowResize, false);
}

/**
 * Events to fire upon window resizing.
 */
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  effect.setSize(window.innerWidth, window.innerHeight);
}

/**
 * Updates to apply to the scene while running.
 */
function update() {
  camera.updateProjectionMatrix();
}

/**
 * Render the scene.
 */
function render() {
  if (stereoEffect === 1) {
    effect.render(scene, camera);
  } else {
    renderer.render(scene, camera);
  }
}

/**
 * Animate the scene.
 */
function animate() {
  requestAnimationFrame(animate);
  update();
  render();
}

$(document).ready(function() {
  
  // Toggle the vr effect.
  $('#stereo-toggle').unbind('click');
  $('#stereo-toggle').click(function() {
    
    
    // Replace the text to hide/show screen.
    if ($('#stereo-toggle').text() == "Turn VR On") {
      stereoEffect = 1;
      onWindowResize();
      $('#stereo-toggle').text('Turn VR Off');
    } else {
      stereoEffect = 0;
      onWindowResize();
      $('#stereo-toggle').text('Turn VR On');
    }
  });
});

That’s all! hopefully, you have successfully created 360 Image Viewer. If you have any questions or suggestions, feel free to comment below.

Leave a Comment