huming0618 / learn-webgl

学习WebGL
0 stars 0 forks source link

了解WebGL #2

Open huming0618 opened 7 years ago

huming0618 commented 7 years ago

参考 https://webglfundamentals.org/

huming0618 commented 7 years ago

WebGL是什么

WebGL is often thought of as a 3D API. People think "I'll use WebGL and magic I'll get cool 3d". In reality WebGL is just a rasterization engine. It draws points, lines, and triangles based on code you supply. Getting WebGL to do anything else is up to you to provide code to use points, lines, and triangles to accomplish your task.

OpenGL的Web接口,一种光栅化渲染引擎

huming0618 commented 7 years ago

Shader

huming0618 commented 7 years ago

Vertex Shader

Example

// an attribute will receive data from a buffer
attribute vec4 a_position;

// all shaders have a main function
void main() {

  // gl_Position is a special variable a vertex shader
  // is responsible for setting
  gl_Position = a_position;
}

对等的js代码解释

var positionBuffer = [
  0, 0, 0, 0,
  0, 0.5, 0, 0,
  0.7, 0, 0, 0,
];
var attributes = {};
var gl_Position;

drawArrays(..., offset, count) {
  var stride = 4;
  var size = 4;
  for (var i = 0; i < count; ++i) {
     // copy the next 4 values from positionBuffer to the a_position attribute
     attributes.a_position = positionBuffer.slice((offset + i) * stride, size);
     runVertexShader();
     ...
     doSomethingWith_gl_Position();
}
huming0618 commented 7 years ago

fragment shader

Example

// fragment shaders don't have a default precision so we need
// to pick one. mediump is a good default. It means "medium precision"
precision mediump float;

void main() {
  // gl_FragColor is a special variable a fragment shader
  // is responsible for setting
  gl_FragColor = vec4(1, 0, 0.5, 1); // return redish-purple
}