On the front end we can animate the DOM by changing its style. We can also animate in WebGL. We can also animate texture maps by changing texture coordinates. The implementation code is as follows. We only need to modify two areas from the texture demo to achieve texture animation.

  • Modify theassignValuefunction

Gl.bufferdata is no longer called to pass data to the buffer.

function assignValue(gl, program) {
    let positions = new Float32Array([-0.5, -0.5.0.0,
    -0.5.0.5.0.1.0.5.0.5.1.1,
    -0.5, -0.5.0.0.0.5.0.5.1.1.0.5, -0.5.1.0,]);// Find the global variable u_Color in the shader;
    var u_Texture = gl.getUniformLocation(program, "u_Texture");
    var a_Position = gl.getAttribLocation(program, "a_Position");
    var a_Uv = gl.getAttribLocation(program, "a_Uv");

    gl.enableVertexAttribArray(a_Position);
    gl.enableVertexAttribArray(a_Uv);
    // Create buffer
    var buffer = gl.createBuffer();
    // Bind buffer is the current buffer
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    // Sets how the a_Position property reads data from the buffer
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false.16.0);
    // Sets how the a_Uv property reads data from the buffer
    gl.vertexAttribPointer(a_Uv, 2, gl.FLOAT, false.16.8);
    // Pass data to the buffer
    // gl.bufferData(
    // gl.ARRAY_BUFFER,
    // positions,
    // gl.STATIC_DRAW
    // );
    loadTexture(gl, '.. /images/1.jpg', u_Texture, function () { render(gl, positions); })}Copy the code
  • WebGLRendering function

Here, gl.bufferData is called to pass data to the buffer, and since the texture coordinates of the data are constantly changing, the data written to the buffer is constantly being rewritten. RequestAnimationFrame is called to increase the x value of the texture coordinates by 0.005 each time the image is rerendered, resulting in the image moving all the way to the left. Of course, you can also change the Y-axis value to run down or up.

let anim = 0.005;
function render(gl, positions) {
    // Pass data to the buffer
    gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(positions),
        l.STATIC_DRAW
    );
    // Set the clear color to black.
    gl.clearColor(0.0.0.1);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES, 0, positions.length / 4);
    if (positions.length <= 0) return;
    for (let i = 2; i < positions.length; i += 4) {
        positions[i] += anim;
    }
    requestAnimationFrame(() = >{
        render(gl,positions);
    }); 
}
Copy the code

The effect is as follows: