Enable VR in Three.js without any extra files
Join 6000+ Students
Upgrade your programming skills to include Virtual Reality. A premium step-by-step training course to get you building real world Virtual Reality apps and website components. You’ll have access to 40+ WebVR & Unity lessons along with their source code.
Start Learning Now
VR has been a hot topic in the developer community. Three.js is the preferred framework for building WebVR applications. Even other frameworks like Aframe uses Three.js in it.
Let’s learn more about three.js in bite sized pieces to help us build better WebVR applications.
Did you know that Three.js comes with VR powers built in? You can enable VR in Three.js with just a single line.
1 2 3 |
renderer.vr.enabled = true; |
Three.js from version r86 comes with this feature built in. Before this, we had to import additional files like vrEffect.js
and VRControls.js
to make WebVR work with Three.js.
Once the above line is set, we just need to provide eht VRDisplay
to the renderer and it’ll take care of the viewer.
We can make use of the WebVR API to get the VRDisplay
from the browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getVRDisplays ( onDisplay ) { if ( 'getVRDisplays' in navigator ) { navigator.getVRDisplays() .then( function ( displays ) { onDisplay( displays[ 0 ] ); } ); } }, |
Then use it for setting VRDisplay.
1 2 3 4 5 |
getVRDisplay(function(display) { renderer.vr.setDevice(display); }); |
This simple tip can help you to directly use WebVR API using Three.js without fiddling with other files.
We can also extend this script by checking the availability of WebVR in the browser before enabling VR mode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function checkAvailability () { return new Promise( function( resolve, reject ) { if ( navigator.getVRDisplays !== undefined ) { navigator.getVRDisplays().then( function ( displays ) { if ( displays.length === 0 ) { reject('no vr'); } else { resolve(); } }); } else { reject('no vr'); } } ); } |
If the browser supports WebVR, then we can set the VRDisplay
to display the scene in VR mode.
If you liked this tip, don’t forget to share this on social media. Also make sure you’re subscribed to the list so you don’t miss any updates.
Leave a Reply