A Beginner’s Guide to WebGL

Share this article

This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
HTML5 & WebGL Join the discussion on Reddit. WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D computer graphics and 2D graphics within any compatible web browser without the use of plug-ins. You will often find developers using it for games, but it is finally gaining widespread visibility across the web, and is now being used for map visualizations, charting data, and even presentations. First introduced in early 2011, this is similar OpenGL ES, the mobile version of OpenGL, but built inside of the browser. Desktop browsers have really started to support it as of late, as have mobile browsers. I wrote about the current state of it (as of November 2014) here. 3d canvas graphics usability

How Many People Are Using WebGL?

User pyalot on reddit has pointed me towards an excellent site for tracking WebGL usage and statistics: https://webglstats.com/. WebGL Stats uses a tracker frame embedded in other sites to collect the data. You can help too, just embed the code below into your page.

<script src="//cdn.webglstats.com" defer="defer" async="async"></script>

What is WebGL Doing and Why Should I Care?

WebGL has three distinct advantages over writing code that simply manipulates the DOM:
  • Tasks. Drawing reflective materials or complex lighting generate a ton of overhead, and seeing that JavaScript is single threaded and CPU bound, why not offload some of that to the GPU in your device and have that do the heavy lifting?
  • Performance.Utilizing hardware acceleration (the GPU built into your device), WebGL is a great fit for games or complex visualizations.
  • Shaders.Complex visual effects can be produced with small programs known as “shaders”. This may be as simple as producing a sepia coloring effect, or more complex simulations such as water or flames. Visit Shadertoy for a showcase of some examples which really highlight this.

Asm.js and Emscripten

asm.js and emscripten Unity, and Epic’s Unreal Engine, the popular middleware tools frequently used by game developers are not limited to creating compiled applications that run as an executable. Unity previously had a web player, which was a downloadable plugin that used ActiveX. Chrome killed support for NPAP (Netscape Plugin API), but announced it over one year ago. In April, with the release of Chrome 42 stable, they finally put the axe to it. There are a number of reasons as to why, but most notably they stated “hangs, crashes, security incidents, and code complexity.” Google suggests using web standards instead, such as WebGL, which I will explain below. Microsoft is following suit and deprecating ActiveX, VBScript, attachEvent, and other legacy technologies in favor of web standards. The need for ActiveX controls has been significantly reduced by HTML5-era capabilities, which also produces interoperable code across browsers. With the advent of WebGL and now asm.js, developers can now harness much of the power of their computing device from within the browser and access markets previously unavailable. JavaScript is the only language which works in all web browsers. Although only JavaScript will run in the browser, you can still write in other languages and still compile to JavaScript, thereby allowing it to also run in the browser. This is made possible by a technology known as emscripten. Emscripten is an LLVM based project that compiles C and C++ into highly performant JavaScript in the asm.js format. In short: near native speeds, using C and C++, inside of the browser. Even better, emscripten converts OpenGL, a desktop graphics API, into WebGL, which is the web variant of that API. I have an in-depth tutorial on how to use emscripten, as well as a clear explanation of what asm.js is.

Exporting a Unity Game to WebGL with Asm.js

Unity games on Azure

WebGL Showcase

Score RushXona Games

beginners-guide-webgl05-score-rush-xona-games This 2D top-down shooter is headed to the Playstation 4, but that didn’t stop it from appearing on the Xbox 360 and even in the browser through Turbulenz‘s WebGL framework first. This Xona Games title runs at 60 frames per second and can draw tens of thousands of particles on screen at once. Moreover, 4-player simultaneous co-op is available, and you can drop in at any point. Who says that there aren’t console-quality games in the browser?

Dolby Audio Room

Dolby Audio Room The Dolby Audio Room was built using WebGL to provide an interactive environment where users can explore and play content on a variety of media devices (a media PC, desktop, laptop and tablet). Each device demonstrates Dolby Audio with a different streaming video, either MPEG DASH H.264 or HLS. The demo currently requires Microsoft Edge, since it is the first browser to include native support for Dolby Audio.

World Flights

World Flights This demo is provided by Sencha Labs to showcase PhiloGL, and is a great showcase for how you can use WebGL to visualize data. In this case, it is active flights across the world.

Monopoly – PlayCanvas

Monopoly - PlayCanvas
If you find someone who doesn’t enjoy Monopoly, you let me know, because they are the anomaly.

WebGlSamples.org

WebGLsamples.org This site has some fantastic collections to play with. I’m not sure of who put this page together, but they some neat demos, such as the book (cloth simulation) and Electric Flower.

How Do I Get Started?

Here are the essentials steps to create create your first WebGL project:
  1. Create <canvas> element
  2. Obtain drawing context
  3. Initialize viewport
  4. Create buffers
  5. Create matrices
  6. Create shaders
  7. Initialize shaders
  8. Draw primitives
I know what you’re thinking: “This sounds like a lot of work. There’s got to be a better way”, and there is! Take a look at some of the engines below.

Engines and Frameworks

BabylonJS

Babylon.js Babylon is an open source and free framework created by several folks at Microsoft as a fun side project. This is updated on nearly a daily basis, and even offers a sandbox to play in and test out your code. Here is a video course broken up into several parts, to get you started with BabylonJS and WebGL.

PlayCanvas

PlayCanvas PlayCanvas is an open source engine which includes a bevy of options, including an editor to help visualize your changes as you make them. Some useful experiences they highlight include brand experiences for viewing high performance cars, as well as playable ads which you can inject into applications. It was also used for the largest game of Space Invaders ever made!

Turbulenz

Turbulenz Turbulenz offers a 2D and 3D engine for developers to build, publish, and monetize games on their platform. Founded by former developers at Electronic Arts, this tool is also open source under the MIT License. Download and build the latest Turbulenz Engine directly from the Github public repository. This includes everything from rendering effects and particles, to physics, animations, audio, inputs, and networking. Their developer page offers a ton of information to get you started. James Austin, the CEO of Turbulenz, has a great write up about the engine on Gamasutra.

Pixi.js

Pixi.js Pixi.js is a devoted rendering engine. There are a host of other engines covering game, sound and physics etc. and they all work beautifully with Pixi. It also has a number of added benefits including render auto-detect to fallback to Canvas when necessary, text support via bitmap (sprites) or webfont, as well as an asset loader.

Phaser.io

Phaser.io Phaser is also open source (fork it on GitHub) and even offers TypeScript support, which is a strongly typed version of JavaScript. I’ve found this to be great when working with developers who are familiar with C-style languages. It also has some in-depth guides, and a showcase of Phaser made games.

Construct 2

Construct 2 This is the framework that I use most often when working with high school or university aged students who have never programmed a game before, largely due to the excellent editor. Developers can easily drag-and-drop all of their assets into the scene and view the properties in an easy to view pane. Even better, it comes with a ton of templates and samples to get started. Ashley Gullen has a great post on how WebGL works with this program as well.

Three.js

Three.js ThreeJS is one of the more popular frameworks, and includes everything you need to get running: renders, scenes, cameras, animations, and lights. While this is fantastic for most things, it is lacking a physics engine, which will came in handy when creating a game. Three.js is made available under the MIT license. It even has an editor (beta) that you can play around in!

PhiloGL

PhiloGL
PhiloGL is a WebGL Framework for Data Visualization, Creative Coding and Game Development from the folks at Sencha Labs. . All lessons from Learning WebGL have been ported into the PhiloGL Framework. This is a great starting point for people wanting to learn PhiloGL and/or WebGL as well. This is also licensed under the MIT License.

Will It Work on Consoles?

David Rousset (@davrous), a Program Manager at Microsoft who is working with Edge, had a great blog post this week where he showcased BabylonJS running on an Xbox One. As of November 12th, a new update is available on Xbox One. As a web developer, I’m more than happy to now have Microsoft Edge running on my console! This means that you can now run very modern content inside the Xbox One browser! You can also remote debug the application using VorlonJS. Vorlon.js is an open-source cross-platforms remote debugging tool that has been made to easily remote debug any web page running on any device. WebGL also works on the Playstation 4. In fact, their UX is largely powered by WebGL. From Don Olmstead, one of the head architects at Sony:
When you login to your PS4 you are running #WebGL code. The PlayStation Store, the Music and Video Applications, as well as a good chunk of UX are all rendered within the browser. I spent a good amount of time tuning our WebGL rendering engine, and I will be speaking at+SFHTML5 about how to optimize WebGL usage within the context of that work. There will be plenty of great tips on how you can speed up your own WebGL applications so get your slot now.
This talk from Google Developers offers a great overview of how it works on their platform. Silicon Angle also has a great article on the topic.

Podcasts

Podcasts If podcasts are your thing, I’ve covered WebGL with a couple of developers before as well. My peer in Chicago, David Giard, has a video podcast called “Technology and Friends”. During the MVP Open Days event in Philadelphia a few months ago, I had a chance to hop on and talk about WebGL, in addition to that, we cover asm.js, and how middleware tools like Unity and Unreal Engine are using asm to allow their applications to run in the browser. On my own podcast, The Indie Dev Podcast, I interviewed my co-worker, David Catuhe (@DeltaKosh), who is a Principal Program Manager on Microsoft’s TED team in Redmond. He is one of the master minds behind the BabylonJS WebGL framework,

Looking to Learn More?

Here are some of the better resources I’ve found on the internet for learning WebGL:

More Hands-on with Web Development

This article is part of the web development series from Microsoft evangelists and engineers on practical JavaScript learning, open source projects, and interoperability best practices including Microsoft Edge browser and the new EdgeHTML rendering engine. We encourage you to test across browsers and devices including Microsoft Edge – the default browser for Windows 10 – with free tools on dev.microsoftedge.com: More in-depth learning from our engineers and evangelists:
  • Interoperability best practices (series):
Our community open source projects: More free tools and back-end web dev stuff: Code with node.JS with trial on Azure Cloud

Frequently Asked Questions (FAQs) about WebGL

What is the difference between WebGL and other 3D graphics APIs?

WebGL is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. Unlike other 3D graphics APIs, WebGL is integrated directly into the web environment, allowing full integration with other web standards. This means you can combine 3D graphics with text, images, and other HTML elements on your web page. WebGL is also based on OpenGL ES 2.0, making it familiar to many developers who have worked with 3D graphics before.

How can I check if my browser supports WebGL?

You can check if your browser supports WebGL by visiting the website get.webgl.org. If your browser supports WebGL, you will see a spinning cube. If not, you will be given instructions on how to enable it or update your browser. You can also check the WebGL Report website for a detailed report of your browser’s WebGL capabilities.

Why is my WebGL application running slowly?

There could be several reasons why your WebGL application is running slowly. It could be due to inefficient rendering, such as drawing too many objects or using complex shaders. It could also be due to memory issues, such as using too much memory for textures or buffers. To improve performance, try to optimize your rendering, reduce memory usage, and use WebGL extensions when available.

Can I use WebGL on mobile devices?

Yes, WebGL is supported on many modern mobile devices. However, the performance and features available may vary depending on the device and the web browser. To ensure the best compatibility and performance, it is recommended to test your WebGL application on multiple devices and browsers.

How can I learn WebGL?

There are many resources available to learn WebGL. You can start with the WebGL specification on the Khronos Group website, which provides a detailed description of the API. There are also many tutorials and examples available online, such as the ones on the Mozilla Developer Network and WebGL Fundamentals websites. Additionally, there are several books and online courses that cover WebGL in depth.

What are the security implications of using WebGL?

Like any web technology, WebGL has potential security risks. These include the possibility of executing malicious code or accessing sensitive information on the user’s system. However, web browsers implement several security measures to mitigate these risks, such as the same-origin policy and context isolation. It is also recommended to keep your web browser up-to-date to benefit from the latest security updates.

Can I use WebGL with other web technologies?

Yes, WebGL can be used in combination with other web technologies, such as HTML, CSS, and JavaScript. This allows you to create rich and interactive web applications that combine 3D graphics with other web content. For example, you can use WebGL to render 3D models in a canvas element, and then use CSS and JavaScript to control the appearance and behavior of the models.

How can I debug WebGL applications?

Debugging WebGL applications can be challenging due to the low-level nature of the API. However, there are several tools and techniques that can help. For example, you can use the WebGL Inspector extension for Chrome, which provides a variety of debugging features. You can also use the WebGLRenderingContext.getShaderInfoLog and WebGLRenderingContext.getProgramInfoLog methods to get information about shader compilation and linking errors.

What are the limitations of WebGL?

While WebGL is a powerful tool for creating 3D graphics on the web, it does have some limitations. These include limited support for older browsers and devices, performance and memory limitations, and lack of support for some advanced graphics features. However, many of these limitations can be overcome with careful programming and use of WebGL extensions.

What is the future of WebGL?

The future of WebGL looks promising. The API is continuously being improved and extended, with new features and extensions being added regularly. There is also a growing community of developers and artists who are creating amazing WebGL applications and sharing their knowledge and techniques. Furthermore, the upcoming WebGPU standard promises to bring even more power and flexibility to web-based graphics.

David VoylesDavid Voyles
View Author

Dave Voyles is a Technical Evangelist for Microsoft. He spends a lot of time writing games, writing about games, and writing about how to write games for the game dev community, Read his blog or follow him on Twitter.

computer graphicsguide to WebGLJavascript APImdnWeb Graphics LibraryWebGL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week