WebGLについて⑤
コンテキストの初期化
コンテキストの取得から初期化まで
- htmlソース要素を
getElementById
を使って取得 - 取得したcanvas要素を使ってWebGLコンテキストを取得する。これをするには
getContext
メソッドを利用する - 画面をクリアするには
clear
メソッドを使い、引数には画面上の色をクリアするので組み込み定数のCOLOR_BUFFER_BIT
のみを指定する
上記例のJavaScriptコード
script.js
onload = function(){ // canvasエレメントを取得 var c = document.getElementById('canvas') // 画面サイズを適当に決める c.width = 500 c.height = 300 // webglコンテキストを取得 var gl = c.getContext('webgl') || c.getContext('experimental-webgl'); // canvasを黒でクリア(初期化)する gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); };
このJavaScriptコードをhtml側で読み込めばブラウザで500×300の黒い領域が表示される(添付図参照)
sample.html
<html> <head> <title>WebGL TEST</title> <script src="script.js" type="text/javascript"></script> </head> <body> <canvas id="canvas"></canvas> </body> </html>
【添付図】