初めての WebGL
とりあえず初期化。これからなんか書く。MDN 頼り(・∀・)
HTML
<canvas id="glcanvas" width="240" height="480">
キミのブラウザは canvas 要素に対応してないみたいだ(・ω・`)
</canvas>
CSS
canvas {
border: 1px solid #fff;
-moz-box-shadow: #000 2px 2px 5px;
box-shadow: #000 2px 2px 5px;
width: 240px;
height: 480px;
background-color: black;
}
JavaScript
var canvas, gl;
function start() {
canvas = document.getElementById("glcanvas");
initWebGL(canvas);
if (gl) {
gl.clearColor(0.0, 0.0, 010, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}
}
function initWebGL() {
gl = null;
try {
gl = canvas.getContext("webgl");
} catch (e) {}
if (!gl) alert("キミのパソ子かブラウザはWebGLに対応してないみたいだ(・ω・`)");
}
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs"),
vertexShader = getShader(gl, "shader-vs");
// shaderプログラムの作成
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// shaderプログラムの作成に失敗したらアラート
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) alert("Unable to initialize the shader program.");
gl.useProgram(shaderProgram);
vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(vertexPositionAttribute);
}
function getShader(gl, id) {
var shaderScript, theSource, currentChild, shader;
shaderScript = document.getElementById(id);
if (!shaderScript) return null;
theSource = "";
currentChild = shaderScript.firstChild;
while (currentChild) {
if (currentChild.nodeType == currentChild.TEXT_NODE) theSource += currentChild.textContent;
currentChild = currentChild.nextSibling;
}
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null; // Unknown shader type
}
gl.shaderSource(shader, theSource);
gl.compileShader(shader); // Compile the shader program
// See if it compiled successfully
if (!gl.getShaderParameter(shader,...