From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/pt-br/web/api/webgl_api/index.html | 278 +++++++++++++++++++++ .../index.html | 226 +++++++++++++++++ .../tutorial/getting_started_with_webgl/index.html | 71 ++++++ files/pt-br/web/api/webgl_api/tutorial/index.html | 39 +++ 4 files changed, 614 insertions(+) create mode 100644 files/pt-br/web/api/webgl_api/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/index.html (limited to 'files/pt-br/web/api/webgl_api') diff --git a/files/pt-br/web/api/webgl_api/index.html b/files/pt-br/web/api/webgl_api/index.html new file mode 100644 index 0000000000..97e1e97857 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/index.html @@ -0,0 +1,278 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) é uma API do JavaScript para renderizar gráficos 3D e 2D dentro de um navegador web compatível sem o uso de plug-ins. O WebGL faz isso introduzindo uma API que está de acordo com o OpenGL ES 2.0 e que pode ser usada em elementos do HTML5 {{HTMLElement("canvas")}}.

+
+ +

O suporte para WebGL está presente no Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ e Internet Explorer 11+. No entanto, o dispositivo do usuário também deve ter um hardware que suporte esses recursos.

+ +

O elemento {{HTMLElement("canvas")}} é também usado pelo Canvas 2D para renderizar gráficos 2D em páginas web.

+ +

Referências

+ +

Interfaces padrão

+ +
+ +
+ +

Extensões

+ +
+ +
+ +

Eventos

+ + + +

Constantes e tipos

+ + + +

WebGL 2

+ +

O WebGL 2 é uma atualização importante para o WebGL, que é fornecida através da interface {{domxref ("WebGL2RenderingContext")}}. Baseia-se no OpenGL ES 3.0 e os novos recursos incluem:

+ + + +

Veja também os posts WebGL 2 lands in Firefox e webglsamples.org/WebGL2Samples para alguns exemplos de demonstração.

+ +

Guias e tutoriais

+ + + +

Tutoriais avançados

+ + + +

Recursos

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Definição inicial. Baseada em OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Criada com base no WebGL 1. Baseada em OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ +

Compatibilidade em navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico9{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}11125.1
WebGL 256{{CompatNo}}{{CompatGeckoDesktop("51")}}{{CompatNo}}43{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico25{{CompatVersionUnknown}}4{{CompatNo}}128.1
WebGL 2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Notas sobre compatibilidade

+ +

Além do navegador, a própria GPU também precisa suportar o recurso. Por exemplo, o S3 Texture Compression (S3TC) só está disponível em tablets baseados em Tegra. A maioria dos navegadores disponibiliza o contexto WebGL usando o nome de contexto webgl, mas navegadores antigos também precisam do nome de contexto experimental-webgl. Além disso, o futuro WebGL 2 é totalmente retrocompatível e terá o nome de contexto webgl2.

+ +

Notas sobre o Gecko

+ +

Debugando e testando WebGL

+ +

Iniciando com o Gecko 10.0 {{geckoRelease("10.0")}}, há duas preferências disponíveis que permitem controlar as funcionalidades do WebGL, para efeitos de teste:

+ +
+
webgl.min_capability_mode
+
Uma propriedade booleana que, quando configurada para true, habilita um modo de capacidade mínima. Neste modo, o WebGL é configurado para suportar somente um conjunto básico de recursos e funcionalidades requeridos pela especificação WebGL. Isto garante que o código WebGL funcione em qualquer dispositivo ou navegador, independente de suas funcionalidades. Esta propriedade tem o valor false por padrão.
+
webgl.disable_extensions
+
Uma propriedade booleana que, quando configurada para true, desabilita todas as extensões WebGL. Esta propriedade tem o valor false por padrão.
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html new file mode 100644 index 0000000000..7b4f6384f6 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html @@ -0,0 +1,226 @@ +--- +title: Adicionando conteúdo 2D a um contexto WebGL +slug: Web/API/WebGL_API/Tutorial/Adicionando_conteudo_2D_a_um_contexto_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

+ +

Uma vez que você tenha  criado um contexto WebGL com sucesso, você pode iniciar a renderizar nele. O mais simples que podemos fazer é desenhar um objeto 2D não texturizado. Então vamos começar por aí, construindo o código necessário para se desenhar um quadrado.

+ +

Desenhando a cena

+ +

A coisa mais importante para se entender antes de começarmos é que, mesmo que estejamos só renderizando um objeto bidimensional nesse exemplo, nós ainda estamos desenhamos em um espaço 3d. Portanto, ainda precisamos estabelecer os shaders que irão criar a cor para a nossa cena simples, assim como desenhar o objeto. Eles irão estabelecer como o quadrado irá aparecer na tela.

+ +

Inicializando os shaders

+ +

Shaders são especificados ao usar a Linguagem de Shading OpenGL ES. Com o intuito de tornar mais fácil para manter e atualizar nosso conteúdo, nós podemos escrever nosso código que carrega os shaders para buscá-los no documento HTML, ao invés de termos de criar tudo em JavaScript. Vamos dar uma olhada na nossa rotina initShaders(), que cuida dessa tarefa:

+ +
function initShaders() {
+  var fragmentShader = getShader(gl, "shader-fs");
+  var vertexShader = getShader(gl, "shader-vs");
+
+  // Cria o progrma shader
+
+  shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // Se falhar ao criar o progrma shader, alerta
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert("Não foi possível inicializar o programa shader.");
+  }
+
+  gl.useProgram(shaderProgram);
+
+  vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
+  gl.enableVertexAttribArray(vertexPositionAttribute);
+}
+
+
+ +

Dois programas estão sendo inicializados por essa rotina; o primeiro, fragment shader, é carregado a partir do elemento HTML com o id "shader-fs". O segundo, vertex shader, é carregado pelo elemento HTML com o id "shader-vs". Nós vamos analisar a função getShader() no próximo tutorial; Essa rotina, na verdade, lida com a parte de puxar os programas shader da DOM.

+ +

Então nós criamos o programa shader chamando do objeto WebGL a função createProgram(), anexamos dois shaders nele e fazemos o link com o programa shader. Depois de fazer isso, o parametro LINK_STATUS do objeto g1 é checado para ter certeza de que o link foi criado com sucesso; Se sim, nós ativamos o novo programa shader.

+ +

Carregando os shaders da DOM

+ +

A rotina getShader() busca um programa shader com o nome específico do DOM, retornando o programa shader compilado para o requisitante, ou null se ele não pode ser carregado ou compilado.

+ +
function getShader(gl, id) {
+  var shaderScript, theSource, currentChild, shader;
+
+  shaderScript = document.getElementById(id);
+
+  if (!shaderScript) {
+    return null;
+  }
+
+  theSource = "";
+  currentChild = shaderScript.firstChild;
+
+  while(currentChild) {
+    if (currentChild.nodeType == currentChild.TEXT_NODE) {
+      theSource += currentChild.textContent;
+    }
+
+    currentChild = currentChild.nextSibling;
+  }
+
+ +

Uma vez que o elemento com o ID específico é encontrado, seu texto é lido na variável theSource.

+ +
  if (shaderScript.type == "x-shader/x-fragment") {
+    shader = gl.createShader(gl.FRAGMENT_SHADER);
+  } else if (shaderScript.type == "x-shader/x-vertex") {
+    shader = gl.createShader(gl.VERTEX_SHADER);
+  } else {
+     // Tipo de shader desconhecido
+     return null;
+  }
+ +

Uma vez que o código para o shader tenha sido lido, nós observamos o tipo MIME do objeto shader para determinar se é um sombreamento de vértice (MIME type "x-shader/x-vertex") ou um fragmento de shader (MIME type "x-shader/x-fragment"), em seguinda crie um tipo de shader apropriado para a partir do código fonte recuperado.

+ +
  gl.shaderSource(shader, theSource);
+
+  // Compile o programa shader
+  gl.compileShader(shader);
+
+  // Veja se ele compila com sucesso
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+      alert("Um erro ocorreu ao compilar os shaders: " + gl.getShaderInfoLog(shader));
+      return null;
+  }
+
+  return shader;
+}
+
+ +

Finalmente, a fonte é passada para o shader e compilada. Se um erro ocorrer enquanto o shader estiver compilando, nós mostraremos um alerta e retornaremos null; Caso contrário, o shader recém compilado é retornado para o requisitante.

+ +

Os shaders

+ +

Agora, nós precisamos adicionar os programas shaders ao HTML para descrever nosso documento. Os detalhes sobre como os shaders trabalham estão além do escopo deste artigo, assim como a sintaxe da linguagem do shader.

+ +

Fragmentos shader

+ +

Cada pixel é um poligono chamado de fragmento (fragment) na linguagem GL. O trabalho do fragmento de shader é estabelecer a cor de cada pixel. Ness caso, nós estamos apenas definindo a cor branca para cada pixel.

+ +

g1_FragColor é um construtor de variável GL que é utilizado para a cor do fragmento. Altere seu valor para definir a cor do pixel, como mostrado abaixo.

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  void main(void) {
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+  }
+</script>
+
+ +

Vértice do shader

+ +

A vértice (vertex) do shader define a posição e a forma de cada vértice.

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+  }
+</script>
+
+ +

Criando um objeto

+ +

Before we can render our square, we need to create the buffer that contains its vertices. We'll do that using a function we call initBuffers(); as we explore more advanced WebGL concepts, this routine will be augmented to create more -- and more complex -- 3D objects.

+ +
var horizAspect = 480.0/640.0;
+
+function initBuffers() {
+  squareVerticesBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+
+  var vertices = [
+    1.0,  1.0,  0.0,
+    -1.0, 1.0,  0.0,
+    1.0,  -1.0, 0.0,
+    -1.0, -1.0, 0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
+}
+
+ +

This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store the vertices. This is then bound to the context by calling the bindBuffer() method.

+ +

Once that's done, we create a JavaScript array containing the coordinates for each vertex of the square. This is then converted into an array of WebGL floats and passed into the gl object's bufferData() method to establish the vertices for the object.

+ +

Desenhando a cena

+ +

Once the shaders are established and the object constructed, we can actually render the scene. Since we're not animating anything in this example, our drawScene() function is very simple. It uses a few utility routines we'll cover shortly.

+ +
function drawScene() {
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+  loadIdentity();
+  mvTranslate([-0.0, 0.0, -6.0]);
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+  setMatrixUniforms();
+  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+}
+
+ +

The first step is to clear the context to our background color; then we establish the camera's perspective. We set a field of view of 45°, with a width to height ratio of 640/480 (the dimensions of our canvas). We also specify that we only want objects between 0.1 and 100 units from the camera to be rendered.

+ +

Then we establish the position of the square by loading the identity position and translating away from the camera by 6 units. After that, we bind the square's vertex buffer to the context, configure it, and draw the object by calling the drawArrays() method.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

Operações úteis da Matrix

+ +

Matrix operations are complicated enough. Nobody really wants to write all the code needed to handle them on their own. Fortunately, there's Sylvester, a very handy library for handling vector and matrix operations from JavaScript.

+ +

The glUtils.js file used by this demo is used by a number of WebGL demos floating around on the Web. Nobody seems entirely clear on where it came from, but it does simplify the use of Sylvester even further by adding methods for building special types of matrices, as well as outputting HTML for displaying them.

+ +

In addition, this demo defines a few helpful routines to interface with these libraries for specific tasks. What exactly they do is beyond the scope of this demo, but there are plenty of good references on matrices available online; see the {{ anch("See also") }} section for a list of a few.

+ +
function loadIdentity() {
+  mvMatrix = Matrix.I(4);
+}
+
+function multMatrix(m) {
+  mvMatrix = mvMatrix.x(m);
+}
+
+function mvTranslate(v) {
+  multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
+}
+
+function setMatrixUniforms() {
+  var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
+  gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));
+
+  var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
+  gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
+}
+
+ +

Ver Também

+ + + +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..4abbd5e304 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,71 @@ +--- +title: Começando com WebGL +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

+ +

WebGL permite que o contéudo web use uma API baseada em OpenGL ES 2.0 para realizar renderização 3D em um canvas HTML em browsers que o suportam sem o uso de plugins. Programas WebGL consistem em um código de controle escrito em JavaScript e códigos de efeitos especiais (shader code) que é executado na Unidade Gráfica de Processamento (GPU) de um computador. Elementos WebGL podem ser utilizados junto com outros elementos HTML e com outras partes da página ou do fundo.

+ +

Esse artigo vai introduzir o básico sobre o uso do WebGL. Acredita-se que você já possui entendimento da matemática que envolve os gráficos 3D, e que este artigo não tem a pretensão de tentar ensinar-lhe OpenGL em si.

+ +

Os exemplos de código deste tutorial também podem ser encontrados no Exemplos de WebGL no repositório do GitHub.

+ +

Preparando-se para renderizar em 3D

+ +

A primeira coisa que você precisa para para renderização do WebGL, é a inicialização do canvas. O fragmento HTML abaixo declara um canvas em que nosso exemplo será desenhado.

+ +
<body>
+  <canvas id="glCanvas" width="640" height="480"></canvas>
+</body>
+
+ +

Preparando o contexto WebGL

+ +

A função main() em nosso código JavaScript é chamada quando nosso script é carregado. O objetivo é configurar o contexto do WebGL e começar a renderizar o conteúdo.

+ +
main();
+
+//
+// começa aqui
+//
+function main() {
+  const canvas = document.querySelector("#glCanvas");
+  // Inicializa o contexto GL
+  const gl = canvas.getContext("webgl");
+
+  // Só continua se o WebGL estiver disponível e funcionando
+  if (!gl) {
+    alert("Incapaz de inicializar o WebGL.Seu navegador ou sua máquina não suporta.");
+    return;
+  }
+
+  // Define a cor para preto totalmente opaca (sem transparência)
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  // Limpa o buffer de cores com uma cor específica
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}
+
+
+ +

A primeira coisa que nós fazemos aqui é obter a referência para o canvas, atribuindo-a para a variável chamada canvas.

+ +

Uma vez que nós temos o canvas, nós tentamos obter um WebGLRenderingContext para ele chamando o getContext e passando a string "webgl". Se o browser não suportar o webgl getContext vai retornar null nesse caso nós mostraremos uma mensagem para o usuário e sair.

+ +

Se o contexto for inicializado com sucesso, a variável gl é nossa referência para ele. Nesse caso, nós altermos a cor para preto, e o contexto para aquela cor (redesenhando o canvas com a cor de fundo).

+ +

Nesse ponto, você tem código suficiente para o contexto WebGL ser inicializado com sucesso, e você deve visualizar uma grande caixa preta vazia, pronta e esperando para receber conteúdo.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

Veja o código completo | Abra a demo em uma nova página

+ +

Veja também

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/index.html b/files/pt-br/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..4fa7ba76cf --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,39 @@ +--- +title: WebGL tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML {{HTMLElement("canvas")}} in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code(shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

+
+ +

This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content.

+ +

Before you start

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

In this tutorial

+ +
+
Getting started with WebGL
+
How to set up a WebGL context.
+
Adding 2D content to a WebGL context
+
How to render simple flat shapes using WebGL.
+
Using shaders to apply color in WebGL
+
Demonstrates how to add color to shapes using shaders.
+
Animating objects with WebGL
+
Shows how to rotate and translate objects to create simple animations.
+
Creating 3D objects using WebGL
+
Shows how to create and animate a 3D object (in this case, a cube).
+
Using textures in WebGL
+
Demonstrates how to map textures onto the faces of an object.
+
Lighting in WebGL
+
How to simulate lighting effects in your WebGL context.
+
Animating textures in WebGL
+
Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.
+
-- cgit v1.2.3-54-g00ecf