How to create a sphere with WebGL

In this post I will describe how you can create sphere with pre3d JavaScript library (http://deanm.github.com/pre3d/). So it will look like:

pre3d sphere

Demo

You will need to include these pre3d JavaScript files:

<script src="lib/pre3d.js"></script>
<script src="lib/pre3d_shape_utils.js"></script>
<script src="lib/demo_utils.js"></script>
<script src="sphere.js"></script>

In addition you will need to place somewhere in the body tag next code:

<canvas id="canvas" width="800" height="600">
Sorry, this demo requires a web browser which supports HTML5 canvas!
</canvas>

It will create canvas placeholder, where we will place our drawings.

As you can see we have attached sphere.js file. In this file we placed our main logic:

window.addEventListener('load', function() {
    var black = new Pre3d.RGBA(0, 0, 0, 1);

    var screen_canvas = document.getElementById('canvas');
    var renderer = new Pre3d.Renderer(screen_canvas);

    var sphere = Pre3d.ShapeUtils.makeSphere(10,30,20);

    function draw() {
      renderer.fill_rgba = new Pre3d.RGBA(0,255,0,0.2);
      renderer.bufferShape(sphere);

      renderer.ctx.setFillColor(0, 0, 0, 1);
      renderer.drawBackground();

      renderer.drawBuffer();
      renderer.emptyBuffer();
    }

    renderer.camera.focal_length = 2.5;

    // Have the engine handle mouse / camera movement for us.
    DemoUtils.autoCamera(renderer, 0, 0, -30, 0.40, -1.06, 0, draw);

    draw();
}, false);

As you can see we call our drawings only when page loaded (we added event listener for ‘load’ event). After that we define black color. It is created with special Pre3d function RGBA(). Right after that we take canvas element and create renderer with our canvas as a parameter. With Pre3d.ShapeUtils.makeSphere(10,30,20) we create sphere with radius 10. After that we define drawing function, which is filling our sphere with semi-transparent green color, buffering our shape, sets scene color, draws all the scene and cleaning the buffer. After that we are setting the camera. After applying DemoUtils.autoCamera() we are able to move camera with mouse. And in the end we are calling our draw() function. When you try to drag the sphere with mouse you will see that sphere will be re-drawn.

And that’s it!

Demo

I hope it is helpful and easy to understand.