Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
105 lines (93 sloc) 2.87 KB
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>sample01</title>
</head>
<body>
<h1>Hello, World! Hello, WebGL!</h1>
<canvas id="canvas"></canvas>
<script type="x-shader/x-vertex" id="vert">#version 300 es
in vec3 position;
in vec3 inColor;
out vec3 color;
uniform mat4 transform;
void main() {
gl_Position = transform * vec4(position, 1.0);
color = inColor;
}
</script>
<script type="x-shader/x-fragment" id="frag">#version 300 es
precision mediump float;
in vec3 color;
out vec4 outColor;
void main() {
outColor = vec4(color, 1.0);
}
</script>
<script>
window.onload = () => {
// Step 1 canvasの取得とサイズの設定
const cvs = document.getElementById('canvas');
cvs.width = 500;
cvs.height = 500;
// Step 2 描画コンテキストの取得とバッファの初期化
const gl = cvs.getContext('webgl2');
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
// Step 3 シェーダプログラムの設定
function getShader(type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
}
const program = gl.createProgram();
const vertexShader =
getShader(gl.VERTEX_SHADER, document.getElementById('vert').text);
gl.attachShader(program, vertexShader);
const fragmentShader =
getShader(gl.FRAGMENT_SHADER, document.getElementById('frag').text);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
// Step 4 VBOにデータの転送
function transferData(data, loc) {
gl.enableVertexAttribArray(loc);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
}
gl.useProgram(program);
const position = [
0.0, 1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0
];
const positionLoc = gl.getAttribLocation(program, 'position');
transferData(position, positionLoc);
const color = [
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
];
const inColorLoc = gl.getAttribLocation(program, 'inColor');
transferData(color, inColorLoc);
// Step 5 uniform変数の値を設定
const transform = [
0.5, 0, 0, 0,
0, 0.5, 0, 0,
0, 0, 0.5, 0,
0, 0, 0, 1
];
const transformLoc = gl.getUniformLocation(program, 'transform');
gl.uniformMatrix4fv(transformLoc, false, transform);
// Step 6 描画
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
</script>
</body>
</html>
You can’t perform that action at this time.