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

这里有两个问题:您没有获得上下文,并且您没有正确处理该故障。

  1. WebGLDebugUtils.makeDebugContext不测试是否给定了实际的上下文,因此如果getContext返回 null,它会产生一个无用的对象,其行为与您所看到的一样。您应该首先测试您是否成功获得了 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 上下文,您可能想尝试使用名称“experimental-webgl”以及“webgl”。例如,Chrome 不支持上下文名称“webgl”。

于 2012-07-15T23:31:51.207 回答