Skip to content

Basic Tutorial

typewriter1 edited this page Sep 18, 2018 · 10 revisions

This tutorial shows how to load and render 3D models in a canvas element.

Setup

Create an HTML page, with a canvas element. Give it an ID value, for example, canvas:

<canvas id="canvas"></canvas>

Download and unzip gl-matrix and wegl-obj-loader, and download the zip of this project and unzip it too.

Include this somewhere in your page:

<script src="path-to-gl-matrix/dist/gl-matrix-min.js"></script>
<script src="path-to-webgl-obj-loader/dist/webgl-obj-loader.min.js"></script>
<script src="webglobjects.js"></script>
<script src="webgllib.js"></script>
<script src="program.js"></script>

program.js is the program we will write.

Initialising the engine

engine.setWebglContext("#canvas");
var game = new engine.Game(gl);

This tells the engine which canvas element to use, and creates a Game object which will be used later on to store the scene and render it.

Compiling the default shader

const shaderProgram = engine.compileShader(engine.defaultVertexShader, engine.defualtFragmentShader);

The shaders define how objects will look. The default shader contains basic texturing and directional lighting. You could also provide your own shader in GLESL, WebGl's shading language.

Creating the camera

var camera = new Camera(game);

The camera defines the viewpoint from which the scene is rendered. Moving the camera will adjust the view of the scene. Cameras are a type of entity and, like all entities, they take the game object as a parameter.

Creating a model

Create the model in a 3D modelling tool such as blender and export it to .obj. Add this to your program.

MODEL_SRC = (Copy and paste the content of the .obj file here)

Loading the model

var model = new Entity(game);
game.scene.push(model);
var renderer = new Renderer(model);
renderer.setModel(engine.loader.model(MODEL_SRC));
renderer.setTexture(engine.loader.texture("models/gun.jpg"););
renderer.setShader(shaderProgram);

This creates a new empty Entity, adds it to the scene and attaches a Renderer component to it. It then sets the model, texture and shader on it.