www.jiazhengblog.com/blog/2017/0…

precision highp float;
attribute vec3 aPos;
attribute vec3 aOffset;
attribute vec3 aColor;
varying vec3 vColor;
void main(void) {gl_Position = vec4(aPos + aOffset, 1);
    vColor = aColor;
}
Copy the code
precision highp float;
varying vec3 vColor;
void main(void) {
    gl_FragColor = vec4(vColor, 1.0);
}
Copy the code
  • Create a copy of vertex data
// vertex representing the triangle
var vertex = [
    -1., -1..0.1.,  -1..0.1..1..0,
    -1., -1..0.1..1..0,
    -1..1..0
];
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertex), gl.STATIC_DRAW);
var aVertexPosition = gl.getAttribLocation(glProgram, 'aPos');
// point the attribute to the currently bound vertex buffer.
gl.vertexAttribPointer(aVertexPosition, 3, gl.FLOAT, false.0.0);
gl.enableVertexAttribArray(aVertexPosition);
Copy the code
  • Create ten copies of Uniform data
// Create buffer for color and displacement
var colorsArray = [];
var offsetsArray = [];
for (var i = 0; i < 10; i++) {
    colorsArray.push(Math.random(), Math.random(), Math.random());
    offsetsArray.push((i - 5) / 5 + 0.1.0.0);
}
Copy the code
  • extension
ext = gl.getExtension("ANGLE_instanced_arrays");
Copy the code
  • Ten copies of uniform offset data +vertexAttribDivisorANGLE setting
  • ext.vertexAttribDivisorANGLE(aOffsetLocation, 1);
var colors = new Float32Array(colorsArray);
var offsets = new Float32Array(offsetsArray);
var aOffsetLocation = gl.getAttribLocation(glProgram, 'aOffset');
var offsetBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, offsetBuffer);
gl.bufferData(gl.ARRAY_BUFFER, offsets, gl.STATIC_DRAW);
gl.enableVertexAttribArray(aOffsetLocation);
gl.vertexAttribPointer(aOffsetLocation, 3, gl.FLOAT, false.12.0);
ext.vertexAttribDivisorANGLE(aOffsetLocation, 1);
Copy the code
  • Ten copies of Uniform color data +vertexAttribDivisorANGLE setting
  • ext.vertexAttribDivisorANGLE(aColorLocation, 1);
var colorBuffer = gl.createBuffer();
var aColorLocation = gl.getAttribLocation(glProgram, 'aColor');
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
gl.enableVertexAttribArray(aColorLocation);
gl.vertexAttribPointer(aColorLocation, 4, gl.FLOAT, false.12.0);
ext.vertexAttribDivisorANGLE(aColorLocation, 1); //
Copy the code
  • drawcall
var instanceCount = 10;
ext.drawArraysInstancedANGLE(gl.TRIANGLES, 0.6, instanceCount);
Copy the code

  • Make the change
ext.vertexAttribDivisorANGLE(aColorLocation, 2); 
Copy the code

  • If you draw using the index, then please use drawElementsInstancedANGLE method