1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【HTML】WebGLでとりあえず直線を引く【WebGL/2D】

Posted at

WebGLで2Dのとりあえず線を引くサンプルです。
丸写しで動きます。
ライブラリ不要です。
IE11,Edge,Chromeで動作確認済みです。
ネットにあるサンプルを変更したのはプログラムのエントリポイントぐらいです。
document.addEventListener('DOMContentLoaded',function() {//実質ここからプログラムが動く});

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=yes">
<title>webgl2d sample</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
	var canvas = document.getElementById("canvas");
	canvas.width = 500;
	canvas.height = 500;
	var gl = canvas.getContext("webgl") || canvas.getContext('experimental-webgl');
	gl.clearColor(1.0, 0.0, 1.0, 1.0); //Red,Green,Blue,Alpha
	gl.clear(gl.COLOR_BUFFER_BIT);

	var buffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

	var vSource = [
	"precision mediump float;",
	"attribute vec2 vertex;",
	"void main(void) {",
	"gl_Position = vec4(vertex, 0.0, 1.0);",
	"}"
	].join("\n");
	var vShader = gl.createShader(gl.VERTEX_SHADER);
	gl.shaderSource(vShader, vSource);
	gl.compileShader(vShader);
	gl.getShaderParameter(vShader, gl.COMPILE_STATUS);

	var rgba = [0.0, 0.0, 0.0, 1.0] // Red, Green, Blue, Alpha
	var fSource = [
	    "precision mediump float;",
	    "void main(void) {",
	    "gl_FragColor = vec4("+ rgba.join(",") +");",
	    "}"
	].join("\n");
	var fShader = gl.createShader(gl.FRAGMENT_SHADER);
	gl.shaderSource(fShader, fSource);
	gl.compileShader(fShader);
	gl.getShaderParameter(fShader, gl.COMPILE_STATUS);

	var program = gl.createProgram();
	gl.attachShader(program, vShader);
	gl.attachShader(program, fShader);
	gl.linkProgram(program);
	gl.getProgramParameter(program, gl.LINK_STATUS);
	gl.useProgram(program);

	var vertex = gl.getAttribLocation(program, "vertex");
	gl.enableVertexAttribArray(vertex);
	gl.vertexAttribPointer(vertex, 2, gl.FLOAT, false, 0, 0);

	var vertices = [
	    -1 , 0, //x,y
	    1 , 0 //x,y
	];
	var verticesNum = vertices.length / 2;

	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.DYNAMIC_DRAW);
	gl.drawArrays(gl.LINE_LOOP, 0, verticesNum);
});

</script>
</head>
<body style="text-align: center; width: 100%; height: 100%;">
<canvas id="canvas"></canvas>
</body>
</html>

こんな感じで表示されるはずです。
webgl2dsample.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?