WebGL Simple Lighting Tutorial

Easiest Method

Introduction

This tutorial explains how to prepare very simple WebGL Lighting.
In this example shaders apply lighting based on the
X and Y vertex coordinates.
This lesson covers the vertex and fragment shaders
for the
WebGL Simple Lighting on a Sphere example.

A number of initialization details were left out, to focus on the main topic.
Most WebGL projects initialize as
described in the WebGL e-book series.
However information in this tutorial should apply to other WebGL projects, such as those that use
Unity or three.js, as well.

The Vertex Shader

The vertex shader calculates values of light and dark
based on X and Y vertex coordinates.
The varyings v_light and v_dark
then pass those calculations to the fragment shader.
The following listing includes the entire
vertex shader.

The Fragment Shader

The fragment shader simply subtracts
from each color channel, the
dark value received through varying
v_dark.
The shader uses the light value
passed through varying v_light
as the alpha value.
For more detailed shader lighting information
please see the
Specular Light Tutorial: Vertex Shader Processing.
The following listing includes the entire fragment shader.

WebGL Sphere Preparation

The sphere was created in 3ds Max, exported as a Collada DAE file,
then translated with JavaScript for use with WebGL.
The JavaScript converter slows down with large numbers of vertices.
Therefore the sphere, in this example, is modeled with just sixteen segments.
The Glowing Earth
example loads a smoother sphere converted with the free WebGL Translator.

Summary

This tutorial explained how to prepare very simple WebGL Lighting.
In this example shaders apply lighting based on X and Y vertex coordinates.
This lesson covered the vertex and fragment shaders
for the
WebGL Simple Lighting on a Sphere example.