{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/webgl-ecosystem-core-api/",
  "atlas": "https://www.pystone.net/?node=webgl-ecosystem-core-api#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/webgl-ecosystem-core-api.md",
  "context": "https://www.pystone.net/notes/webgl-ecosystem-core-api.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:webgl-ecosystem-core-api",
  "slug": "webgl-ecosystem-core-api",
  "title": "P1 WebGL生态地图与核心API",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML <canvas in browsers that support it without the use of plug ins.",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "9c1e35062243c96fe031816575524b6f3360e4ebc1cc4677c05f45e4e1d1ca5c",
  "assets": [
    {
      "reference": "assets/image-20250512232206264.png",
      "url": "/media/86912608e0956a6835e5.png",
      "mediaType": "image/png",
      "contentHash": "86912608e0956a6835e5686ad18f49afd65afa8f00c6b8ca018b2376d3ccb1ef",
      "byteLength": 27964,
      "width": 1029,
      "height": 483
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "P1 WebGL生态地图与核心API",
      "anchor": "p1-webgl生态地图与核心api",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#p1-webgl%E7%94%9F%E6%80%81%E5%9C%B0%E5%9B%BE%E4%B8%8E%E6%A0%B8%E5%BF%83api"
    },
    {
      "depth": 3,
      "text": "0 核心原理",
      "anchor": "0-核心原理",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#0-%E6%A0%B8%E5%BF%83%E5%8E%9F%E7%90%86"
    },
    {
      "depth": 3,
      "text": "1 浏览器‑GPU 渲染链",
      "anchor": "1-浏览器gpu-渲染链",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#1-%E6%B5%8F%E8%A7%88%E5%99%A8gpu-%E6%B8%B2%E6%9F%93%E9%93%BE"
    },
    {
      "depth": 3,
      "text": "2 WebGL 与 OpenGL ES 关系",
      "anchor": "2-webgl-与-opengl-es-关系",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#2-webgl-%E4%B8%8E-opengl-es-%E5%85%B3%E7%B3%BB"
    },
    {
      "depth": 3,
      "text": "3 GLSL ES 语法要点",
      "anchor": "3-glsl-es-语法要点",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#3-glsl-es-%E8%AF%AD%E6%B3%95%E8%A6%81%E7%82%B9"
    },
    {
      "depth": 3,
      "text": "4 四步搞定最小渲染",
      "anchor": "4-四步搞定最小渲染",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#4-%E5%9B%9B%E6%AD%A5%E6%90%9E%E5%AE%9A%E6%9C%80%E5%B0%8F%E6%B8%B2%E6%9F%93"
    },
    {
      "depth": 3,
      "text": "5 环境配置 & 操作方法",
      "anchor": "5-环境配置-操作方法",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#5-%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE-%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95"
    },
    {
      "depth": 3,
      "text": "6 三角形完整示例 + 行内注释",
      "anchor": "6-三角形完整示例-行内注释",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#6-%E4%B8%89%E8%A7%92%E5%BD%A2%E5%AE%8C%E6%95%B4%E7%A4%BA%E4%BE%8B-%E8%A1%8C%E5%86%85%E6%B3%A8%E9%87%8A"
    },
    {
      "depth": 3,
      "text": "7 DevTools 调试要领",
      "anchor": "7-devtools-调试要领",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#7-devtools-%E8%B0%83%E8%AF%95%E8%A6%81%E9%A2%86"
    },
    {
      "depth": 3,
      "text": "Reference",
      "anchor": "reference",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#reference"
    },
    {
      "depth": 2,
      "text": "相关工具",
      "anchor": "相关工具",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#%E7%9B%B8%E5%85%B3%E5%B7%A5%E5%85%B7"
    },
    {
      "depth": 2,
      "text": "调试",
      "anchor": "调试",
      "citation": "https://www.pystone.net/notes/webgl-ecosystem-core-api/#%E8%B0%83%E8%AF%95"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:game-graphics-and-runtime",
      "title": "游戏图形与运行时",
      "url": "https://www.pystone.net/notes/game-graphics-and-runtime/",
      "atlas": "https://www.pystone.net/?node=game-graphics-and-runtime#knowledge-atlas",
      "label": "游戏图形与运行时",
      "origin": "explicit",
      "humanReviewed": true,
      "context": "WebGL中的“P1 WebGL生态地图与核心API”导航项",
      "citation": "https://www.pystone.net/notes/game-graphics-and-runtime/#webgl"
    }
  ],
  "contentMarkdown": "[WebGL](https://www.khronos.org/webgl/) enables web content to use an API based on [OpenGL ES](https://www.khronos.org/opengles/) 2.0 to perform 3D rendering in an HTML `<canvas>` in browsers that support it without the use of plug-ins.\n\nWebGL 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).\n\nWebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.\n# P1 WebGL生态地图与核心API\n### 0 核心原理\n\n状态机:\nWebGL is really just an API to run shaders. The only functions that actually write pixels are `gl.clear`, `gl.drawArrays` and `gl.drawElements`. That's it! All other API calls just setup internal state for when those 3 functions are called.\n\n顶点和片段Shader:\nWebGL only cares about 2 things: clip space coordinates and colors. Your job as a programmer using WebGL is to provide WebGL with those 2 things. You provide your 2 \"shaders\" to do this. A Vertex shader which provides the clip space coordinates, and a fragment shader that provides the color.\n![](assets/image-20250512232206264.png)\n\n\n---\n\n### 1 浏览器‑GPU 渲染链\n\n```text\nJS 源码 ─┐\n          ↓  (1) JavaScript 解释/编译 (V8/SpiderMonkey…)\n **WebGL API 调用**  ──────────▶  (2) WebGL 驱动层\n                                         │   把状态、顶点、uniform 等写入\n                                         │   GPU Command Buffer\n                                         ▼\n                                  (3) GPU 驱动\n                                         │   真正执行顶点 / 光栅 / 片元着色器\n                                         ▼\n                                  (4) 帧缓冲 → 屏幕\n```\n\n* **DOM 树** 并不参与这条链；WebGL 只依赖 `<canvas>` 提供的像素缓冲。\n* 调用链中能被你直接编写的只有：\n\n  1. **JavaScript 逻辑**（WebGL API）\n  2. **GLSL 着色器**（GPU 端程序）\n\n---\n\n### 2 WebGL 与 OpenGL ES 关系\n\n* **WebGL 1.0 ≈ OpenGL ES 2.0**（固定管线消失，全部靠顶点/片元着色器）。\n* **WebGL 2.0 ≈ OpenGL ES 3.0**，带来：\n\n  * **VAO**（Vertex Array Object）\n  * **UBO**（Uniform Buffer Object）\n  * **Instanced Draws**\n  * 多渲染目标（MRT）等高级特性。\n* 判断浏览器支持：\n\n  ```js\n  const gl2 = canvas.getContext('webgl2');   // null ⇒ 只支持 WebGL1\n  ```\n\n  ([MDN Web Docs][1])\n\n---\n\n### 3 GLSL ES 语法要点\n\n| 关键字                        | 作用          | WebGL1 vs WebGL2                     |\n| -------------------------- | ----------- | ------------------------------------ |\n| `attribute`                | 逐顶点输入       | **仅 WebGL1**；在 WebGL2 用 `in`         |\n| `uniform`                  | 所有顶点/片元共享参数 | 相同                                   |\n| `varying`                  | 顶点→片元插值     | WebGL1 用 `varying`，WebGL2 用 `out/in` |\n| `precision mediump float;` | 片元默认精度      | 片元着色器必须指定精度                          |\n\nGLSL 程序在运行前 **编译 + 链接**，否则 GPU 无法执行。([The Khronos Group][2])\n\n---\n\n### 4 四步搞定最小渲染\n\n1. **获取 WebGL Context**\n\n   ```js\n   const gl = canvas.getContext('webgl');     // 或 'webgl2'\n   if (!gl) throw 'WebGL unsupported!';\n   ```\n2. **编译着色器**\n\n   ```js\n   const vs = gl.createShader(gl.VERTEX_SHADER);\n   gl.shaderSource(vs, vertexSource);\n   gl.compileShader(vs);\n   ```\n\n   相同流程对片元着色器 (`gl.FRAGMENT_SHADER`)。\n3. **链接程序并激活**\n\n   ```js\n   const prog = gl.createProgram();\n   gl.attachShader(prog, vs);  gl.attachShader(prog, fs);\n   gl.linkProgram(prog);  gl.useProgram(prog);\n   ```\n4. **上传数据 + 绘制**\n\n   ```js\n   const buf = gl.createBuffer();\n   gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n   gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([...]), gl.STATIC_DRAW);\n\n   const loc = gl.getAttribLocation(prog, 'aPos');\n   gl.enableVertexAttribArray(loc);\n   gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);\n\n   gl.clearColor(0,0,0,1); gl.clear(gl.COLOR_BUFFER_BIT);\n   gl.drawArrays(gl.TRIANGLES, 0, 3);\n   ```\n\n详细代码见 §6。流程出自 MDN *Getting Started with WebGL* ([MDN Web Docs][3])\n\n---\n\n### 5 环境配置 & 操作方法\n\n1. **编辑器**：VS Code\n2. **本地服务器**：安装扩展“Live Server”，右键 HTML → *Open with Live Server*（避免跨域和文件协议限制）。\n3. **浏览器**：Chrome/Edge 最新版；开启 DevTools > Rendering > *WebGL errors and warnings* 选项可即时捕获 GL 报错。([Chrome for Developers][4])\n\n---\n\n### 6 三角形完整示例 + 行内注释\n\n```html\n<meta charset=\"utf-8\">\n<canvas id=\"c\" width=\"640\" height=\"480\"></canvas>\n<script>\n/// 1. 取 context ————————————————————————\nconst gl = document.getElementById('c').getContext('webgl');\nif (!gl) { alert('WebGL unsupported'); throw 'no gl'; }\n\n/// 2. 写 GLSL 源码 ————————————————————————\nconst vsSrc = `                 // 顶点着色器: 把顶点坐标直接送裁剪空间\nattribute vec2 aPos;\nvoid main() { gl_Position = vec4(aPos, 0.0, 1.0); }`;\n\nconst fsSrc = `                 // 片元着色器: 每个像素涂亮红色\nprecision mediump float;\nvoid main() { gl_FragColor = vec4(1.0, 0.2, 0.2, 1.0); }`;\n\n/// 3. 编译 & 链接 ————————————————————————\nfunction compile(src,type){\n  const s = gl.createShader(type);\n  gl.shaderSource(s, src);  gl.compileShader(s);\n  if(!gl.getShaderParameter(s, gl.COMPILE_STATUS))\n      console.error(gl.getShaderInfoLog(s));\n  return s;\n}\nconst prog = gl.createProgram();\ngl.attachShader(prog, compile(vsSrc, gl.VERTEX_SHADER));\ngl.attachShader(prog, compile(fsSrc, gl.FRAGMENT_SHADER));\ngl.linkProgram(prog); gl.useProgram(prog);\n\n/// 4. 上传顶点 ————————————————————————\nconst buf = gl.createBuffer();\ngl.bindBuffer(gl.ARRAY_BUFFER, buf);\ngl.bufferData(gl.ARRAY_BUFFER,\n  new Float32Array([ 0,0.8,  -0.8,-0.8,  0.8,-0.8 ]),\n  gl.STATIC_DRAW);\n\nconst loc = gl.getAttribLocation(prog, 'aPos');\ngl.enableVertexAttribArray(loc);\ngl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);\n\n/// 5. 清屏并绘制 ————————————————————————\ngl.clearColor(0,0,0,1);       // 背景设黑\ngl.clear(gl.COLOR_BUFFER_BIT); // 清颜色缓冲\ngl.drawArrays(gl.TRIANGLES, 0, 3);\n</script>\n```\n\n运行后看到红色三角即表示管线打通。\n\n---\n\n### 7 DevTools 调试要领\n\n1. **Sources ▶ WebGL**\n\n   * *Shaders* 节点列出已编译 GLSL；点击可查看源码、uniform 值。\n   * *Calls* 面板统计本帧 WebGL API 调用数量。\n2. **Console**\n\n   ```js\n   gl.getParameter(gl.VERSION);      // \"WebGL 1.0 ...\" or \"WebGL 2.0 ...\"\n   gl.getError();                    // 返回错误码 0 OK\n   ```\n3. **Performance ▶ Frames**\n\n   * 录制后展开一帧，可见 CPU script vs GPU raster 时间分布。\n\n详见 Chrome DevTools Rendering & Performance 文档 ([Chrome for Developers][4])\n\n---\n\n\n### Reference\n\n[1]: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext?utm_source=chatgpt.com \"WebGLRenderingContext - Web APIs | MDN - MDN Web Docs\"\n[2]: https://www.khronos.org/opengl/wiki/Fragment_Shader?utm_source=chatgpt.com \"Fragment Shader - OpenGL Wiki - The Khronos Group\"\n[3]: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL?utm_source=chatgpt.com \"Getting started with WebGL - Web APIs | MDN - MDN Web Docs\"\n[4]: https://developer.chrome.com/docs/devtools/rendering/performance/?utm_source=chatgpt.com \"Discover issues with rendering performance - Chrome DevTools\"\n[5]: https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_lose_context?utm_source=chatgpt.com \"WEBGL_lose_context extension - Web APIs | MDN - MDN Web Docs\"\n[6]: https://webglfundamentals.org/docs/?utm_source=chatgpt.com \"Home - Documentation - WebGL Fundamentals\"\n\n\n## 相关工具\n\nJavaScript、HTML 和 CSS在线编辑、测试： https://jsfiddle.net/\n\nthree 学习引导GPT： https://chatgpt.com/g/g-jGjqAMvED-three-js-mentor/\n\n\n## 调试\n\n```text\n在 VS Code 中安装 Live Server 插件。\n右键点击 index.html，选择 “Open with Live Server”。\nVS Code 将在某个端口（默认 5500）启动本地服务器。\n```\n"
}
