Nomisoft
Menu

Three.js 360° photos

18th January 2017

Ever seen those interactive 360° photos that you can rotate, zoom and pan? If you've ever fancied creating one yourself its actually relatively straight forward when using the Three.js library.

For this demonstration I'm using a 360° photo of Brompton Oratory which I found on Wikipedia at https://commons.wikimedia.org/wiki/File:Brompton_Oratory_360x180,_London,_UK_-_Diliff.jpg

Firstly we're going to setup our HTML page which has a single DIV element along with calls to load the relevant JavaScript libraries and our own app.js file.


# index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Three.js 360 Photo Test</title>
    </head>
    <body>
        <div id="scene"></div>
        <script src="three.min.js"></script>
        <script src="OrbitControls.js"></script>
        <script src="app.js"></script>
    </body>
</html>

Now that that is in place we can get to the clever stuff. If you've already used Three.js before this will be quite familiar to you, we're creating a new Three.js scene and adding a camera. We need want to create a sphere shape onto which we're going to project our image. We create a SphereGeometry and load our image onto it as a texture. Finally we add some basic lighting and add some controls to allow us to rotate our photo.


# app.js
var scene;
var camera;
var renderer;
var controls;

function init() {
    var div = document.getElementById("scene");
    var width  = div.offsetWidth;
    var height = div.offsetHeight;

    /* Setup our scene */
    scene = new THREE.Scene();

    /* Setup our camera */
    camera = new THREE.PerspectiveCamera(75, width / height, 1, 1000);
    camera.position.x = 0.1;

    /* Setup our renderer */
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);
    div.appendChild(renderer.domElement);

    /* Setup our sphere with our photo */
    var sphere = new THREE.Mesh(
      new THREE.SphereGeometry(100, 20, 20),
      new THREE.MeshPhongMaterial({
          map: THREE.ImageUtils.loadTexture('photo.jpg')
      })
    );
    sphere.scale.x = -1;
    scene.add(sphere);

    /* Setup lighting */
    scene.add(new THREE.AmbientLight(0xFFFFFF));

    /* Setup controls */
    controls = new THREE.OrbitControls(camera);
    controls.noPan = true;
    controls.noZoom = true;
    controls.autoRotate = true;
    controls.autoRotateSpeed = 0.5;

    render();
}

function render() {
    controls.update();
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}

window.onload = init();

If you liked this short tutorial also check out how to import 3d models into three.js