Originally published at: http://www.sitepoint.com/building-earth-with-webgl-javascript/
Of all the HTML5 and related APIs we’ve been given, WebGL is possibly the most interesting. With it we can create awesome 3D environments right in our browsers, and in this article I’m going to walk you through exactly how to do that.
In particular, we’re going to be building a model of planet Earth that we can rotate around like a crazy person and with which we can wow our fellow developers… well, at least a little.
Before We Begin
For this tutorial we will be using the fantastic three.js WebGL plugin. It’s a bit like jQuery for WebGL in that it abstracts a lot of the processing ugliness inherent in the native API. Put simply, three.js makes our lives a lot easier.
We can include it, just like any normal script in our HTML document, like so:
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r63/three.min.js"></script>
Here we’ve used a CDN, but you could use a local version. We then need to make sure that WebGL has something to render onto. Here we have some flexibility: we can use an ordinary div
or canvas to render directly into the HTML, otherwise we can create and append the canvas later using JavaScript. We’ll go with the first method, to make things a little easier:
<body> <div id="container"></div> <script src="earth.js"></script> </body>
After adding the link to the JavaScript file, our HTML is more-or-less done for now.
The Setup
Three.js itself tends to set things up much like a real 3D desktop program might. We have a scene in which things live, a camera with which to view them, some lighting, a renderer to actually render things, and of course the 3D objects themselves. The list can seem a little daunting, but all of these can take shape as variables within our earth.js
JavaScript file.