Sling Academy
Home/JavaScript/Build VR and AR Experiences with JavaScript WebGL

Build VR and AR Experiences with JavaScript WebGL

Last updated: December 14, 2024

Introduction

Virtual Reality (VR) and Augmented Reality (AR) are at the forefront of transforming how we interact with digital environments. By using JavaScript, a ubiquitous language that powers the web, along with WebGL, a JavaScript API for rendering interactive 3D graphics, developers can create immersive VR and AR experiences directly in the browser. In this article, we'll explore how to harness the power of JavaScript and WebGL to build VR and AR applications.

Getting Started with WebGL

WebGL is a powerful tool integrated into modern web browsers. It allows you to leverage the GPU for rendering complex 3D scenes. First, let’s review how to set up a basic WebGL context. You’ll need a modern web browser and a bit of HTML to get started.

<html>
  <body>
    <canvas id="webgl-canvas" width="800" height="600"></canvas>
    <script src="app.js"></script>
  </body>
</html>
// app.js
const canvas = document.getElementById('webgl-canvas');
const gl = canvas.getContext('webgl');

if (!gl) {
  console.error('WebGL not supported');
}

These simple steps create a basic setup. You have an HTML page with a canvas element and a JavaScript file that initializes the WebGL context.

Creating a Basic Scene

With your WebGL context ready, the next step is preparing it to draw scenes. Set up a simple scene by drawing a triangle, which is the simplest polygon we can create.

// Vertex shader program
const vsSource = `
  attribute vec4 aVertexPosition;
  void main(void) {
    gl_Position = aVertexPosition;
  }`;

// Fragment shader program
const fsSource = `
  void main(void) {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Red color
  }`;

Shaders are programs that run on the GPU, required for WebGL to function. Compile and attach them to a WebGL program:

function loadShader(gl, type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    console.error('An error occurred compiling the shader: ' + gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
    return null;
  }
  return shader;
}

const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, loadShader(gl, gl.VERTEX_SHADER, vsSource));
gl.attachShader(shaderProgram, loadShader(gl, gl.FRAGMENT_SHADER, fsSource));
gl.linkProgram(shaderProgram);

With shaders compiled and linked into a program, prepare a geometry to draw.

const buffers = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffers);

const vertices = [
  0.0,  1.0,  0.0,
  -1.0, -1.0, 0.0,
  1.0, -1.0, 0.0,
];

// Transfer data into buffer
const vertexArray = new Float32Array(vertices);
gl.bufferData(gl.ARRAY_BUFFER, vertexArray, gl.STATIC_DRAW);

Now that you have your basic shader and geometry setup, render into the canvas:

gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.useProgram(shaderProgram);

  const vertexPosition = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
  gl.bindBuffer(gl.ARRAY_BUFFER, buffers);
  gl.vertexAttribPointer(vertexPosition, 3, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(vertexPosition);

  gl.drawArrays(gl.TRIANGLES, 0, 3);

Adding Interactivity for VR/AR

To make the scene interactive and suitable for VR or AR, you can integrate libraries such as Three.js for ease of use or frameworks like A-Frame, which allow building web-based VR and AR experiences with more straightforward structures.

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<a-scene>
  <a-box position="0 1.6 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
</a-scene>

Using A-Frame simplifies deploying VR and AR; all the necessary components are baked into an easy-to-understand, attribute-driven model.

Conclusion

Building VR and AR experiences on the web using JavaScript and WebGL opens up new avenues for creating rich, interactive applications. By mastering basic WebGL constructs, understanding shaders, and leveraging frameworks like A-Frame, you can transform simple web applications into immersive 3D environments. Keep experimenting with different libraries, and remember the only limit is your imagination.

Next Article: Receive One-Time Passwords with the WebOTP API in JavaScript

Previous Article: Combine Shaders and Textures in JavaScript WebGL

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration