1

私は WebGL で開発を始めており、JavaScript をほとんど知りません。WebGL コンテキストを管理するクラスを作成しようとしています。

私は次のものを持っています: 私の HTML ページ:

<!DOCTYPE html>
<html>
   <head>
      <title> Star WebGL  </title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      <link rel="stylesheet" type="text/css" href="estilos/main.css">

      <script type="text/javascript" src="libs/webgl-debug.js"></script>
      <script type="text/javascript" src="libs/clases/Contexto.js"></script>
      <script type="text/javascript" src="libs/applicacion.js"></script>
   </head>

   <body>
      <canvas class="screen" id="screen-canvas"  width="640" height="480">
          </canvas>  
   </body>

</html>

クラスContexto.js:

function Contexto( Canvas )
{
    this.canvas = Canvas;
    this.contextoGL;
    this.contexto_creado = false;   
}

Contexto.prototype.crearContextoWebGL = function ()
{
   try
   {        
      this.contextoGL  = WebGLDebugUtils.makeDebugContext( this.canvas.getContext( "webgl" ) );
      if( !this.contextoGL )
        this.contexto_creado = false;
      else
        this.contexto_creado = true;
   }
   catch( e)
   {
      console.log( "No se puede crear un contexto gl" );
   }
};

Contexto.prototype.contextoCreado = function ()
{
   return this.contexto_creado;
};

Contexto.prototype.getGL = function ()
{
   return this.contextoGL;
};

Contexto.prototype.setColor = function(  r,g,b,a )
{
   this.contextoGL.clearColor( r,g,b,a );   
};

クラスapplicacion.js:

window.onload = main;

function main()
{
   var canvas = document.getElementById( "screen-canvas");
   var contextoWebGL = new Contexto( canvas );
   contextoWebGL.crearContextoWebGL();
   console.log( contextoWebGL.contextoCreado() );
   contextoWebGL.setColor(  0.5161561076529324, 1, 0.7, 1  );
}

背景を変えようとすると、

 contextoWebGL.setColor(  0.5161561076529324, 1, 0.7, 1  )

次のエラーが表示されます。

 Uncaught TypeError: Object #<Object> has no method 'clearColor' 

オブジェクト指向コンテキストを作成するための正しいコードは何ですか?

JavaScript アプリケーションでオブジェクト指向コードを使用する場合、効率は影響を受けますか?

4

1 に答える 1

2

ここには 2 つの問題があります。コンテキストを取得していないことと、その失敗を正しく処理していないことです。

  1. WebGLDebugUtils.makeDebugContext実際のコンテキストが与えられているかどうかをテストしないため、getContextnull を返す場合、見ているように動作する役に立たないオブジェクトが生成されます。最初に WebGL コンテキストを正常に取得したかどうかをテストしてから、 を使用してラップする必要がありmakeDebugContextます。

    this.contextoGL = this.canvas.getContext( "webgl" );
    if( !this.contextoGL ) {
        this.contexto_creado = false;
    } else {
        this.contexto_creado = true;
        this.contextoGL = WebGLDebugUtils.makeDebugContext( this.contextoGL );
    }
    

    これにより、コードはコンテキストの取得に失敗したことを正しく報告します。この構造により、デバッグ コンテキストを使用しないことを選択しやすくなり、パフォーマンスが向上します。

  2. WebGL コンテキストを正常に取得するには、おそらく「webgl」だけでなく「experimental-webgl」という名前を試してください。たとえば、Chrome はコンテキスト名「webgl」をサポートしていません。

于 2012-07-15T23:31:51.207 に答える