ch02/ColoredPoints
Example from the book "WebGL Programming Guide" by Matsuda & Lea
by Ivan Enzhaev
HTML
<canvas id="webgl" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script type="x-shader/x-vertex" id="VertexShader">
attribute vec4 a_Position;
void main()
{
gl_Position = a_Position;
gl_PointSize = 10.0;
}
</script>
<script type="x-shader/x-fragment" id="FragmentShader">
precision mediump float;
uniform vec4 u_FragColor;
void main()
{
gl_FragColor = u_FragColor;
}
</script>
<script src="https://dl.dropboxusercontent.com/s/ylw7v7a44xtrwv0/webgl-utils.js"></script>
<script src="https://dl.dropboxusercontent.com/s/iz1n21c8xafd76n/webgl-debug.js"></script>
<script src="https://dl.dropboxusercontent.com/s/subm1yzylxuao8v/cuon-utils.js"></script>
JavaScript
main();
//window.onload = main;
function main()
{
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl)
{
console.log('Failed to get the rendering context for WebGL');
return;
}
// Get shader elements
var vShaderElement = document.getElementById("VertexShader");
var fShaderElement = document.getElementById("FragmentShader");
if (vShaderElement == null || fShaderElement == null)
{
console.log("Failed to get the shader element");
return;
}
// Get shader source
var vShaderSource = vShaderElement.firstChild.textContent;
var fShaderSource = fShaderElement.firstChild.textContent;
// Initialize shaders
if (!initShaders(gl, vShaderSource, fShaderSource))
{
console.log('Failed to intialize shaders.');
return;
}
// Get the storage location of a_Position
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0)
{
console.log('Failed to get the storage location of a_Position');
return;
}
// Get the storage location of u_FragColor
var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
if (!u_FragColor)
{
console.log('Failed to get the storage location of u_FragColor');
return;
}
// Register function (event handler) to be called on a mouse press
canvas.onmousedown = function (ev) { click(ev, gl, canvas, a_Position, u_FragColor) };
// Specify the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
}
var g_points = []; // The array for the position of a mouse press
var g_colors = []; // The array to store the color of a point
function click(ev, gl, canvas, a_Position, u_FragColor)
{
var x = ev.clientX; // x coordinate of a mouse pointer
...