WebVR Development Tutorial - Standard Getting Started

insert image description here

WebVR is the experience mode of web + VR. This article introduces how to develop a WebVR webpage. Before that, it is necessary for us to understand the experience mode of WebVR.
WebVR experience mode
insert image description here

Ways to experience WebVR

The experience mode of WebVR can be divided into VR mode and naked eye mode

VR mode

1.Mobile VR

If you use cardboard glasses to experience the webVR webpage of the mobile browser, the browser will obtain the tilting and rotating orientation of the user's head according to the parameters of the horizontal gyroscope, and tell the page which orientation scene needs to be rendered.

2.PC VR

By wearing the Oculus Rift detachable headset to browse the web pages connected to the PC host, the browsers that currently support the WebVR API are mainly Firefox Nightly of Firefox and Google chrome beta with VR enabled.

naked eye mode

In addition to the experience mode in VR mode, the method of browsing web pages with naked eyes is also considered here. If the detected user chooses to enter VR mode on the PC side, the user should be able to drag the scene with the mouse, while on the smartphone, the user should be able to drag the scene. Allows the user to use touchmove or tilt the phone to change the perspective of the scene.
The concept of WebVR is probably like this, this time we will use the cardboard + mobile method to test our WebVR scene, and now embark on our development journey.

Preparations
Test tools: smartphone + cardboard headset + chrome beta 60+ (need to enable the WebVR option)
If you have the ability to see the dual-screen of the phone as a single screen with the naked eye, you can also save the headset.

Technology and framework: three.js for WebGL
Three.js is a framework for building 3D scenes. It encapsulates WebGL functions and simplifies the code cost of creating scenes. Using three.js, we can create 3D scenes and 3D animations more elegantly. Here I am using version 0.86. If you want to understand the development of WebVR applications with pure WebGL and the specific environment configuration of WebVR, you can refer to the webvr tutorial - in-depth analysis.

js plugins to be introduced: 1. three.min.js 2. webvr-polyfill.js
webvr-polyfill.js
Since the WebVR API is not yet supported by major browsers, webvr-polyfill.js needs to be introduced to support WebVR web pages , which provides a large number of VR-related APIs, such as the Navigator.getVRDisplay() method to obtain VR headset information.

3D scene construction
First we create an HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0, shrink-to-fit=no">
    <title>webVR-helloworld</title>
    <style type="text/css">
    * {
    
    
	    margin: 0;
	    padding: 0;
    }
    html,body {
    
    
        height: 100%;
        overflow: hidden;
    }
    </style>
</head>
<body>
</body>
<script src="./vendor/three.min.js"></script>
<script src="./vendor/webvr-polyfill.js"></script>
<script></script>
</html>

Next, write a js script to start creating our 3d scene.

1. Create a scene
The scene scene in Three.js is the entire container that draws our 3d objects

var scene = new THREE.Scene();

2. Add a camera

The camera in Three.js represents the user's eyes, and we determine the field of view by setting the FOV,

//定义一个60°的视角,视线范围在1到1000的透视相机
var camera = new THREE. new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,1,1000);
scene.add(camera);

3. Add the renderer
Three.js renderer to render the picture seen by the camera

//初始化渲染器 antialias参数为ture表示开启抗锯齿策略
var renderer = new THREE.WebGLRenderer({
    
     antialias: true } );
//设置渲染器渲染尺寸
renderer.setSize(window.innerWidth,window.innerHeight);
//设置渲染背景为白色
renderer.setClearColor(0xeeeeee);
//将渲染场景的canvas放入body标签里
document.body.appendChild(renderer.domElement);
4.添加一个立方体网格
// 创建立方体
var geometry = new THREE.CubeGeometry( 10,10,10);
var material = new THREE.MeshLambertMaterial( {
    
     color: 0xef6500,needsUpdate: true,opacity:1,transparent:true} );
var cube = new THREE.Mesh( geometry, material );
cube.position.set(0,100,-50);
cube.rotation.set(Math.PI/6,Math.PI/4,0);
scene.add(cube);

5. Start animation
The principle of animation rendering: the renderer continuously calls the drawing method, and the properties of the object are dynamically changed in the method. The old version of three.js needs to manually call the requestAnimationFrame() method to render the animation recursively. The new version of three.js has encapsulated this property, so you only need to pass the renderer renderer.animate(callback).

function update() {
    
    
    //让立方体旋转
    cube.rotation.y += 0.01;
    //渲染器渲染场景,等同于给相机按下快门
    renderer.render(scene, camera);
}
renderer.animate(update);//启动动画

So far, we have drawn a simple 3d scene and made it move. Next, we need to make our scene support WebVR mode.

WebVR scene development
Use navigator.getVRDisplays to get the vr device instance vrdisplay, we need to pass it to the currently running renderer renderer, when you click the button, you can enter VR mode, and click again to exit VR mode.

function initVR(renderer) {
    
    
    renderer.vr.enabled = true;
    navigator.getVRDisplays().then( function(display) {
    
    
        renderer.vr.setDevice(display[0]);
        const button = document.querySelector('.vr-btn');
        VRbutton(display[0],renderer,button,function() {
    
    
            button.textContent = '退出VR';
        },function() {
    
    
            button.textContent = '进入VR';
        });
    }).catch(err => console.warn(err));
}

Here you need to control the current rendering mode logic through the button as follows:

When the button is clicked, according to display.isPresenting, it is judged whether the current rendering is under the VR device. If false, enter 2, otherwise, enter 3.
The current non-VR mode, click the button to enter VR mode, and call display.requestPresent() at this time, When display.isPresenting is set to true, the vrdisplaypresentchange event of the window is triggered.
Currently in VR mode, click the button to exit the mode. At this time, display.exitPresent() is called, display.isPresenting is set to false, and the vrdisplaypresentchange event of the window is triggered.

/**  VR按钮控制
    * @param {
    
    VRDisplay} display VRDisplay实例
    * @param {
    
    THREE.WebGLRenderer} renderer 渲染器
    * @param {
    
    HTMLElement} button VR控制按钮
    * @param {
    
    Function} enterVR 点击进入VR模式时回调
    * @param {
    
    Function} exitVR 点击退出VR模式时回调
    **/
function VRbutton(display,renderer,button,enterVR,exitVR) {
    
    
    if ( display ) {
    
    
        button.addEventListener('click', function() {
    
    
            // 点击vr按钮控制`isPresenting`状态
            display.isPresenting ? display.exitPresent() : display.requestPresent( [ {
    
     source: renderer.domElement } ] );
        });
        window.addEventListener( 'vrdisplaypresentchange', function() {
    
    
            // 是否处于vr体验模式中,是则触发enterVR,否则触发exitVR
            display.isPresenting ? enterVR() : exitVR();
        }, false );
    } else {
    
    
        // 找不到vr设备实例,则移除按钮
        button.remove();
    }
}

We can change the UI of the button according to the value of isPresenting in the vrdisplaypresentchange event, and three.js will decide whether to render normally or in vr mode according to the value of isPresenting. In vr mode, three.js will create two cameras for rendering .

Finally, write the WebVR application as an ES6 class, and standardize the code according to the following figure:

In the first step, the constructor initializes the VR scene, camera and renderer; in the second step, the start method is called before rendering, in which we create 3d objects for the scene; finally, renderer.animate(this.update) is invoked Turn on animation rendering. In the update method, we can dynamically manipulate object properties. The specific code is as follows:

class WebVRApp {
    
    
  constructor() {
    
    
    // 初始化场景
    this.scene = new THREE.Scene();
    // 初始化相机
    this.camera = new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,0.1,1000);
    this.scene.add(this.camera);
 
    // 初始化渲染器
    this.renderer = new THREE.WebGLRenderer({
    
     antialias: true } );
    this.renderer.setSize(window.innerWidth,window.innerHeight);
    this.renderer.setClearColor(0x519EcB);
    this.renderer.setPixelRatio(window.devicePixelRatio);
    document.querySelector('.main-page').appendChild(this.renderer.domElement);
 
    this.clock = new THREE.Clock();
    // VR初始化
    this._initVR();
    // 往场景添加3d物体
    this.start();
    // 窗口大小调整监听
    window.addEventListener( 'resize', this._resize.bind(this), false );
    // 渲染动画
    this.renderer.animate(this.update.bind(this));
  }
  // 创建3d物体
  start() {
    
    
    const {
    
     scene, camera } = this;
    // 创建光线、地面等
    ...
    // 创建立方体
    const geometry = new THREE.CubeGeometry(2, 2, 2);
    const material = new THREE.MeshLambertMaterial({
    
     
      color: 0xef6500,
    });
    this.cube = new THREE.Mesh( geometry, material );
    this.cube.position.set({
    
     x: 0, y: 0, z: -4 });
    scene.add(this.cube);
  }
  // 动画更新
  update() {
    
    
    const {
    
    scene,camera,renderer,clock} = this;
    const delta = clock.getDelta() * 60;
    // 启动渲染
    this.cube.rotation.y += 0.1 * delta;
    renderer.render(scene, camera);
  }
  // VR模式初始化
  _initVR() {
    
    
    const {
    
     renderer } = this;
    renderer.vr.enabled = true;
    // 获取VRDisplay实例
    navigator.getVRDisplays().then( display => {
    
    
    // 将display实例传给renderer渲染器
    renderer.vr.setDevice(display[0]);
    const button = document.querySelector('.vr-btn');
    VRButton.init(display[0],renderer,button,() => button.textContent = '退出VR',() => button.textContent = '进入VR');
    }).catch(err => console.warn(err));
  }
  // 窗口调整监听
  _resize() {
    
    
    const {
    
     camera, renderer } = this;
    // 窗口调整重新调整渲染器
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  }
}
new WebVRApp();

Full code: github.com/YoneChen/WebVR-helloworld.

Conclusion: At present, foreign Google, Firefox, Facebook and domestic Baidu have launched versions that support WebVR browsers, and Microsoft has also announced that it will launch its own VR browser. With the maturity of the platform, the experience of WebVR will be revolutionary. Users can browse online stores through WebVR, and online teaching can conduct "face-to-face" communication between teachers and students. Based on these application scenarios, we can find a better motivation to learn. WebVR.

Reference link: responisve WebVR: Explore the adaptation scheme of WebVR in different head-mounted display (HMD) MolizaVR example: Firefox WebVR example webvr-boilerplate: A starting point for web-based VR experiences that work on all VR headsets. how to build webvr: How to Build VR on the Web Today

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324343780&siteId=291194637