1. 程式人生 > >three.js 全景重力感應

three.js 全景重力感應

實現three.js 全景圖 demo

使用three.js 寫了球體和圓柱體版本的3D重力感應全景圖,支援手指觸控和陀螺儀感應,也支援PC端的滑鼠。給大家介紹一下基於移動端H5球體的實現方法,圓柱體類似。

設定容器和展示的樣式

設定容器的寬高為全屏展示,清除body的margin,引用three.min.js(3D渲染框架) 和orienter.js (陀螺儀經緯度計算)

這裡寫圖片描述

<div id="CanvasBody"></div>

<script src="js/three.min.js"></script>
<!--重力感應-->
<script src="js/orienter.js"></script> <!--動畫效果--> <script src="js/tween.js"></script> <!-- 程式碼 -->
body {margin: 0;}
html, body, #CanvasBody {width: 100vw;height: 100vh;overflow: hidden;}
#CanvasBody {position: relative;}

設定html的data-dpr 屬性,設定html 的fontSize

設定html的fontSize,重新計算body的實際可展示尺寸,這樣可以使渲染出來的畫面更清晰,解析度最完美。

(function(_window) {
    var navigatorUserAgent = navigator.userAgent;
    var iPhone = navigatorUserAgent.indexOf("iPhone");
    if (iPhone > -1) {
        var dpr = Number(window.devicePixelRatio),
                one_dpr = 1 / dpr
    } else {
        var dpr = 1,
            one_dpr = 1
    }
    var
writeText = "<meta name=\"viewport\" content=\"width=device-width,initial-scale=" + one_dpr + ",maximum-scale=" + one_dpr + ",minimum-scale=" + one_dpr + ",user-scalable=no\">\n <meta name=\"'flexible\" content=\"initial-dpr=" + dpr + "\">"; document.write(writeText); var html = document.getElementsByTagName("html"); var F0 = 75; html[0].setAttribute("data-dpr", dpr); var getFontSize = function getFontSize() { var windowWidth = window.innerWidth; html[0].style.fontSize = F0 * windowWidth / 750 + "px" }; getFontSize(); _window.addEventListener("resize", getFontSize, false) })(window);

定義相關變數

var camera,//攝像機
            scene,//舞臺
            renderer,//渲染器
            isUserInteracting = false,//使用者是否正在操作
            onMouseDownMouseX = 0, onMouseDownMouseY = 0,//滑鼠點選的x和Y座標
            lon = 0, onMouseDownLon = 0, onPointerDownLon= 0.0,onPointerDownPointerX = 0,//經度
            lat = 0, onMouseDownLat = 0, onPointerDownLat= 0.0,onPointerDownPointerY = 0,//緯度
            phi = 0, theta = 0,//計算相機位置的重要引數
            o = new Orienter(),//陀螺儀方法物件
            new_longitude=0,last_longitude=0,move_longitude=0,//改變的經度的計算
            new_latitude=0,last_latitude=0,move_latitude=0,//改變的緯度的計算
            is_touch=false,is_start=false,isPlay=true,isMusicPlay=true,tsa=100.1,ppl='';

    var raycaster = new THREE.Raycaster();//拾取場景裡面的物體,可判斷點選或互動事件對應的元素
    var mouse = new THREE.Vector2();//二維向量的物件,滑鼠計算

初始化舞臺的元素和內容

圖片的長寬控制在4096px以內,部分機型效能不夠,渲染不了超大的圖片

 function init() {/**初始化**/
        var container, mesh;//容器和素材
        container = document.getElementById( 'CanvasBody' );//容器
        camera = new THREE.PerspectiveCamera( 72, window.innerWidth / window.innerHeight, 0.01, 1100 );//相機
        camera.target = new THREE.Vector3( 0, 0, 0 );//相機位置

        scene = new THREE.Scene();//舞臺
        scene.updateMatrixWorld(true);
        var geometry = new THREE.SphereGeometry(1, 32, 16);//球體

        geometry.scale( 1, 1, -1 );
        //設定球體的背景貼圖
        var textureBg = new THREE.TextureLoader().load("img/bg.jpg");
        textureBg.generateMipmaps = true;
        textureBg.magFilter = THREE.LinearFilter;//設定貼紙素材的質量
        textureBg.minFilter = THREE.LinearFilter;
        var material = new THREE.MeshBasicMaterial( {
            map: textureBg,//圓柱體貼圖,全景圖
            //color:0xFF0000,
            //transparent: true
        } );
        mesh = new THREE.Mesh( geometry, material );
        //這裡可以設定對應的動畫效果
//        new TWEEN.Tween( mesh).to( {transform:"rotate(90deg)"}, 800 ).repeat( false ).delay( 300 ).yoyo( true ).easing( TWEEN.Easing.Cubic.InOut ).start();
        scene.add( mesh );

        // 旋轉預設 攝影機看到的角度 Start//
        scene.rotation.set(0,0,0); //首頁

        //初始化渲染器,追加到容器
        renderer = new THREE.WebGLRenderer({precision: 'highp' ,mipmap: 'highp',antialias:false});//加上precision 和 mipmap引數,調整畫面清晰度
        renderer.setPixelRatio( window.devicePixelRatio );//設定畫素比
        renderer.setSize( window.innerWidth, window.innerHeight );//設定渲染視窗的大小
        container.appendChild( renderer.domElement );//追加到容器中去

        //滑鼠、手機touch的各個事件
        document.addEventListener( 'mousedown', onDocumentMouseDown, false );
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        document.addEventListener( 'mouseup', onDocumentMouseUp, false );

        document.addEventListener( 'touchstart', onDocumentTouchDown, false );
        document.addEventListener( 'touchmove', onDocumentTouchMove, false );
        document.addEventListener( 'touchend', onDocumentTouchUp, false );
        // document.addEventListener( 'wheel', onDocumentMouseWheel, false );
        //
        document.addEventListener( 'dragover', function ( event ) {
            event.preventDefault();
            event.dataTransfer.dropEffect = 'copy';
        }, false );
        document.addEventListener( 'dragenter', function ( event ) {
            document.body.style.opacity = 0.5;
        }, false );
        document.addEventListener( 'dragleave', function ( event ) {
            document.body.style.opacity = 1;
        }, false );
        document.addEventListener( 'drop', function ( event ) {
            event.preventDefault();
            var reader = new FileReader();
            reader.addEventListener( 'load', function ( event ) {
                material.map.image.src = event.target.result;
                material.map.needsUpdate = true;
            }, false );
            reader.readAsDataURL( event.dataTransfer.files[ 0 ] );
            document.body.style.opacity = 1;
        }, false );
    }

監聽的各事件和方法

//監聽橫豎屏重新設定尺寸
    function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
    function onDocumentMouseDown( event ) {
        event.preventDefault();
        isUserInteracting = true;
        onPointerDownPointerX = event.clientX;
        onPointerDownPointerY = event.clientY;
        onPointerDownLon = lon;
        onPointerDownLat = lat;

        // Click action
        mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
        mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
        raycaster.setFromCamera( mouse, camera );
        var intersects = raycaster.intersectObjects( scene.children );//第一個是最上面一層的元素
        console.log("點選的元素",intersects);
        if ( intersects.length > 0 ) {//如果點到小圓點 就執行回撥函式回撥函式為goto_p
            try {
                intersects[0].object.callback();
            }
            catch(err) {}
        }
    }
    function onDocumentMouseMove( event ) {
        if ( isUserInteracting === true ) {
            lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon;
            lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
        }
    }
    function onDocumentMouseUp( event ) {
        isUserInteracting = false;
    }

    //  touch event start
    function onDocumentTouchDown( event ) {
        is_touch=true;

        event.preventDefault();
        isUserInteracting = true;
        onPointerDownPointerX = event.touches[ 0 ].clientX;
        onPointerDownPointerY = event.touches[ 0 ].clientY;
        if(is_start){
            onPointerDownLon = lon;
            onPointerDownLat = lat;
        }
        // For Click action

        mouse.x = ( onPointerDownPointerX / renderer.domElement.clientWidth ) * 2 - 1;
        mouse.y = - ( onPointerDownPointerY / renderer.domElement.clientHeight ) * 2 + 1;

        raycaster.setFromCamera( mouse, camera );
        var intersects = raycaster.intersectObjects( scene.children );
        console.log('touchDown',lon,lat);
        if ( intersects.length > 0 ) {
            try {
                intersects[0].object.callback();
            }
            catch(err) {}
        }
    }
    function onDocumentTouchMove( event ) {
        if(is_start){
            if ( isUserInteracting === true ) {

                lon = ( onPointerDownPointerX - event.touches[ 0 ].clientX ) * 0.1 + onPointerDownLon;
                lat = ( event.touches[ 0 ].clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
            }
        }
    }
    function onDocumentTouchUp( event ) {
        is_touch=false;
    }
    //  touch event end

    //  set
    function onDocumentTouchDown2( event ) {
        tsa = event.touches[0].clientY;
        console.log( '@:'+event.touches[0].clientY );
        event.preventDefault();

    }
    function onDocumentMouseWheel( event ) {
        camera.fov += event.deltaY * 0.05;
        camera.updateProjectionMatrix();
    }

動畫播放和陀螺儀

function animate() {//播放動畫
        if(isPlay){
            TWEEN.update();
            update();
            requestAnimationFrame( animate );
        }

    }
    o.onOrient = function (obj) {//重力感應計算角度
        if(is_start){
            //最新經度
            new_longitude = obj.lon;
            move_longitude=new_longitude-last_longitude;

            //最新緯度
            new_latitude = obj.lat;
            move_latitude = new_latitude-last_latitude;

            //判斷經緯度
            if(move_longitude>=300){
                move_longitude=move_longitude-361;
            }else if(move_longitude<=-300){
                move_longitude=move_longitude+359;
            }


            if(move_latitude>=300){
                move_latitude=move_latitude-361;
            }else if(move_latitude<=-300){
                move_latitude=move_latitude+359;
            }

            if( is_touch ){
                move_longitude=0;
                move_latitude=0;
            }else{
                move_longitude=move_longitude*0.6;
                move_latitude=move_latitude*0.6;
            }
            //計算得出重力感應的經緯度
            lon=lon-move_longitude;
            last_longitude = obj.lon;
            lat = lat-move_latitude;
            last_latitude = obj.lat;
        }

    };

    function update() {//更新攝像機位置,旋轉平移
        //lat = Math.max( -6, Math.min( 6, lat ) );//設定lat緯度的範圍,只在一個範圍內旋轉
        phi = THREE.Math.degToRad( 90 - lat );
        theta = THREE.Math.degToRad( lon );
        camera.target.x =  500 * Math.sin( phi ) * Math.cos( theta );//X軸的座標
        camera.target.y = 500 * Math.cos( phi );//y軸的座標
        camera.target.z =  500 * Math.sin( phi ) * Math.sin( theta ) ;//z軸的座標
        camera.lookAt( camera.target );
        renderer.render( scene, camera );//重新渲染
    }

執行所有

//執行所有
    is_start=true;
    init();
    o.init();
    animate();

綜上,炫酷的3D重力感應H5就出來啦!