惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

WebGL Fundamentals

WebGL Using 2 or More Textures WebGL Implementing DrawImage WebGL 2D Matrices WebGL Implementing A Matrix Stack WebGL 2D Rotation WebGL 2D Scale WebGL 2D Translation WebGL - Rasterization vs 3D libraries WebGL 3D - Cameras WebGL 3D Geometry - Lathe WebGL 3D - Directional Lighting WebGL 3D - Point Lighting WebGL 3D - Normal Mapping WebGL 3D - Spot Lighting WebGL - Orthographic 3D WebGL 3D Perspective Correct Texture Mapping WebGL 3D Perspective WebGL Textures WebGL and Alpha WebGL - Animation WebGL Anti-Patterns WebGL Attributes WebGL Boilerplate WebGL - Cross Origin Images WebGL Cross Platform Issues WebGL Cubemaps WebGL 3D - Data Textures WebGL - Drawing Multiple Things WebGL Drawing Without Data WebGL Environment Maps (reflections) WebGL Fog WebGL Framebuffers WebGL Fundamentals WebGL GPGPU WebGL How It Works WebGL Image Processing Continued WebGL Image Processing WebGL Optimization - Instanced Drawing WebGL - Less Code, More Fun WebGL Load Obj with Mtl WebGL Load Obj WebGL Matrices vs Math Matrices WebGL Multiple Views, Multiple Canvases WebGL Picking WebGL Planar and Perspective Projection Mapping WebGL Points, Lines, and Triangles WebGL Post Processing WebGL Precision Issues WebGL Pulling Vertices Accessing textures by pixel coordinate in WebGL2 A simple way to show the load on the GPU's vertex and fragment processing? Apply a displacement map and specular map Can anyone explain what this GLSL fragment shader is doing? Can I mute the warning about vertex attrib 0 being disabled? Create image warping effect in WebGL Creating a smudge/liquify effect How to draw Depth Sprites Determine min/max values for the entire image Don't blend a polygon that crosses itself Drawing 2D image with depth map to achieve pseudo-3D effect Drawing a heightmap Drawing layers with different points Drawing Many different models in a single draw call Drawing textured sprites with instanced drawing Efficient particle system in javascript? (WebGL) Emulating palette based graphics in WebGL FPS-like camera movement with basic matrix transformations Get the size of a point for collision checking GLSL shader to support coloring and texturing How can I compute for 500 points which of 1000 line segments is nearest to each point? How can I create a 16bit historgram of 16bit data How can I get all the uniforms and uniformBlocks How can I move the perspective vanishing point from the center of the canvas? How to Achieve Moving Line with Trail Effects How to bind an array of textures to a WebGL shader uniform? How to blend colors across 2 triangles How to combine more text drawing into fewer draw calls How to control the color between vertices How to create a torus How to detect clipped triangles in the framgment shader How to determine the average brightness in a scene? How to draw correctly textured trapezoid polygons How to fade the drawing buffer How to figure out how much GPU work to do without crashing WebGL How to get audio data into a shader How to get code completion for WebGL in Visual Studio Code How to get the 3d coordinates of a mouse click How to get pixelize effect in webgl? How to implement zoom from mouse in 2D WebGL How to import a heightmap in WebGL How to load images in the background with no jank How to make a smudge brush tool How to make WebGL canvas transparent How to optimize rendering a UI How to prevent texture bleeding with a texture atlas How to process particle positions How to read a single component with readPixels How to render large scale images like 32000x32000 How to simulate a 3D texture in WebGL How to support both WebGL and WebGL2
WebGL Indexed Vertices
WebGLFundame · 2025-02-26 · via WebGL Fundamentals

This article assumes you've at least read the article on fundamentals. If you have not read that yet you should probably start there.

This is a short article to cover gl.drawElements. There are 2 basic drawing functions in WebGL. gl.drawArrays and gl.drawElements. Most of the articles on the site that explicitly call one or the other call gl.drawArrays as it's the most straight forward.

gl.drawElements on the other hand uses a buffer filled with vertex indices and draws based on that.

Let's take the example that draws rectangles from the first article and make it use gl.drawElements

In that code we created a rectangle from 2 triangles, 3 vertices each for a total of 6 vertices.

Here was our code that provided 6 vertex positions

  var x1 = x;
  var x2 = x + width;
  var y1 = y;
  var y2 = y + height;
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
     x1, y1,   // vertex 0
     x2, y1,   // vertex 1
     x1, y2,   // vertex 2
     x1, y2,   // vertex 3
     x2, y1,   // vertex 4
     x2, y2,   // vertex 5
  ]), gl.STATIC_DRAW);

We can instead use data for 4 vertices

  var x1 = x;
  var x2 = x + width;
  var y1 = y;
  var y2 = y + height;
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
     x1, y1,  // vertex 0
     x2, y1,  // vertex 1
     x1, y2,  // vertex 2
     x2, y2,  // vertex 3
  ]), gl.STATIC_DRAW);

But, then we need to add another buffer with indices because WebGL still requires that to draw 2 triangles we must tell it to draw 6 vertices in total.

To do this we create another buffer but we use a different binding point. Instead of the ARRAY_BUFFER binding point we use the ELEMENT_ARRAY_BUFFER binding point which is always used for indices.

// create the buffer
const indexBuffer = gl.createBuffer();

// make this buffer the current 'ELEMENT_ARRAY_BUFFER'
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);

// Fill the current element array buffer with data
const indices = [
  0, 1, 2,   // first triangle
  2, 1, 3,   // second triangle
];
gl.bufferData(
    gl.ELEMENT_ARRAY_BUFFER,
    new Uint16Array(indices),
    gl.STATIC_DRAW
);

Like all data in WebGL we need a specific representation for the indices. We convert the indices to unsigned 16 bit integers with new Uint16Array(indices) and then upload them to the buffer.

At draw time we need to bind whatever buffer holds the indices we want to use.

  // bind the buffer containing the indices
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);

And then draw with drawElements

// Draw the rectangle.
var primitiveType = gl.TRIANGLES;
var offset = 0;
var count = 6;
-gl.drawArrays(primitiveType, offset, count);
+var indexType = gl.UNSIGNED_SHORT;
+gl.drawElements(primitiveType, count, indexType, offset);

We get the same results as before but we only had to supply data for 4 vertices instead of 6. We still had to ask WebGL to draw 6 vertices but this let us reuse data for 4 vertices through the indices.

Whether you use indexed or non indexed data is up to you.

It's important to note that indexed vertices won't usually let you make a cube with 8 vertex positions because generally you want to associate other data with each vertex, data that is different depending on which face that vertex position is being used with. For example if you wanted to give each face of the cube a different color you'd need to provide that color with the position. So even though the same position is used 3 times, once for each face a vertex touches, you'd still need to repeat the position, once for each different face, each with a different associated color. That would mean you'd need 24 vertices for a cube, 4 for each side and then 36 indices to draw the required 12 triangles.

Note that valid types for indexType above in WebGL1 are only gl.UNSIGNED_BYTE where you can only have indices from 0 to 255, and, gl.UNSIGNED_SHORT where the maximum index is 65535. There is an extension, OES_element_index_uint you can check for and enable which allows gl.UNSIGNED_INT and indices up to 4294967296.

const ext = gl.getExtension('OES_element_index_uint');
if (!ext) {
  // fall back to using gl.UNSIGNED_SHORT or tell the user they are out of luck
}

According to WebGLStats nearly all devices support this extension.

Note: Above we bind the indexBuffer to the ELEMENT_ARRAY_BUFFER binding point when putting the indices in the buffer then we bind it again later. Why bind it twice?

This is only to show a pattern. Typically you'd be drawing more than a single thing so you'd have multiple index buffers, one for each thing you want to draw. At init time you'd create these buffers and put data in them. At render time, before you draw each individual thing you'd need to bind the correct buffer. So, the code here follows that pattern even though it's only drawing one thing.