首页 > 解决方案 > 如何使用 WebGL 设置动画速度

问题描述

我想通过改变平移增量来设置非常简单的动画的速度(只是在屏幕上向下移动一个 2D 矩形)。该代码基于“@greggman's”很棒的 WebGL 课程系列https://webglfundamentals.org/webgl/lessons/webgl-animation.html

我可以很好地渲染矩形,并且可以让它在屏幕上移动。问题是,最初,它移动得太快了,所以我尝试添加更多、更精细的翻译增量来减慢速度。但是,当我将增量(循环)的数量增加太多时,屏幕会冻结/暂停以进行计算,当它恢复活力时,它将矩形定位在循环结束的位置,而不是稳定地渲染帧-逐帧。(感觉好像浏览器——Firefox——只是想找到结束位置并渲染它,而不是花时间逐步浏览每一帧)。

这是我试图用来控制动画速度的循环。

 var inc = -0.0001;
  for (var ii = 0; ii < 1000000; ++ii) {
    translation[1] += inc;
// If at boundaries, reverse direction . . . 
    switch (translation[1]) {
        case 1:
            inc = -inc;
        case -1:
            inc = -inc;
    }
    drawScene();
  }

这是drawScene():

function drawScene() {
    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    // Tell WebGL how to convert from clip space to pixels
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    // Clear the canvas.
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Tell it to use our program (pair of shaders)
    gl.useProgram(program);

    // Turn on the attribute
    gl.enableVertexAttribArray(positionLocation);

    // Bind the position buffer.
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

    // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
    var size = 2;          // 2 components per iteration
    var type = gl.FLOAT;   // the data is 32bit floats
    var normalize = false; // don't normalize the data
    var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
    var offset = 0;        // start at the beginning of the buffer
    gl.vertexAttribPointer(
        positionLocation, size, type, normalize, stride, offset);

    // set the resolution
    gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);

    // set the color
    gl.uniform4fv(colorLocation, color);

    // Set the translation.
    gl.uniform2fv(translationLocation, translation);

    // Draw the geometry.
    var primitiveType = gl.TRIANGLES;
    var offset = 0;
    var count = 9;  // 3 triangles in the 'F', 3 points per triangle
    gl.drawArrays(primitiveType, offset, count);
  }
}

非常感谢如果有任何想法如何使动画逐帧平滑渲染,同时让我控制动画的速度!. . .

标签: webgl

解决方案


就像它在您链接到的文章中显示的那样,您需要使用requestAnimationFrame. requestAnimationFrame接受回调,并传递自页面加载以来的时间(以毫秒为单位)。然后,您根据时间或自上一帧以来的时间更新用于计算位置或旋转或大小或颜色或任何值的任何值。

所以例如

let then = 0;
function render(now) {
   now *= 0.001;  // convert to seconds
   const deltaTime = now - then;   // deltaTime is now number of seconds since last frame
   then = now;    // save the for the next frame

   // now update some values. Example

   positionX += moveSpeed * deltaTime; 
   rotation += rotateSpeed * deltaTime;

   // then draw your stuff using those values

   webgl goes here

   // now loop by calling requestAnimationFrame to call this function again
   requestAnimationFrame(render)
}

// start the loop
requestAnimationFrame(render)

这是您使用上面的循环发布的代码。不过请注意,我看到您使用的代码来自关于翻译的文章。你真的应该使用矩阵,所以请继续阅读

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  var canvas = document.getElementById("canvas");
  var gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  // setup GLSL program
  var program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);
  gl.useProgram(program);

  // look up where the vertex data needs to go.
  var positionLocation = gl.getAttribLocation(program, "a_position");

  // lookup uniforms
  var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
  var colorLocation = gl.getUniformLocation(program, "u_color");
  var translationLocation = gl.getUniformLocation(program, "u_translation");

  // Create a buffer to put positions in
  var positionBuffer = gl.createBuffer();
  // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  // Put geometry data into buffer
  setGeometry(gl);

  var translation = [0, 0];
  var color = [Math.random(), Math.random(), Math.random(), 1];

  function drawScene() {
    webglUtils.resizeCanvasToDisplaySize(gl.canvas);

    // Tell WebGL how to convert from clip space to pixels
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    // Clear the canvas.
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Tell it to use our program (pair of shaders)
    gl.useProgram(program);

    // Turn on the attribute
    gl.enableVertexAttribArray(positionLocation);

    // Bind the position buffer.
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

    // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
    var size = 2; // 2 components per iteration
    var type = gl.FLOAT; // the data is 32bit floats
    var normalize = false; // don't normalize the data
    var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position
    var offset = 0; // start at the beginning of the buffer
    gl.vertexAttribPointer(
      positionLocation, size, type, normalize, stride, offset);

    // set the resolution
    gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);

    // set the color
    gl.uniform4fv(colorLocation, color);

    // Set the translation.
    gl.uniform2fv(translationLocation, translation);

    // Draw the geometry.
    var primitiveType = gl.TRIANGLES;
    var offset = 0;
    var count = 18; // 12 triangles in the 'F', 3 points per triangle
    gl.drawArrays(primitiveType, offset, count);
  }
  
  let moveSpeed = 100;  // in units per second
  
  webglLessonsUI.setupSlider("#moveSpeed", {value: moveSpeed, slide: updateMoveSpeed, min: 0, max: 400});

  function updateMoveSpeed(event, ui) {
     moveSpeed = ui.value;
  }  
  
  let then = 0;
  function render(now) {
     now *= 0.001;  // convert to seconds
     const deltaTime = now - then;   // deltaTime is now number of seconds since last frame
     then = now;    // save the for the next frame

     // now update some values. Example

     translation[0] += moveSpeed * deltaTime; 
     translation[1] += moveSpeed * deltaTime; 
     
     // keep them on the screen
     translation[0] %= gl.canvas.width;
     translation[1] %= gl.canvas.height;

     // then draw your stuff

     drawScene()

     // now loop by calling requestAnimationFrame to call this function again
     requestAnimationFrame(render);
  }

  // start the loop
  requestAnimationFrame(render);  


}


// Fill the buffer with the values that define a letter 'F'.
function setGeometry(gl) {
  gl.bufferData(
      gl.ARRAY_BUFFER,
      new Float32Array([
          // left column
          0, 0,
          30, 0,
          0, 150,
          0, 150,
          30, 0,
          30, 150,

          // top rung
          30, 0,
          100, 0,
          30, 30,
          30, 30,
          100, 0,
          100, 30,

          // middle rung
          30, 60,
          67, 60,
          30, 90,
          30, 90,
          67, 60,
          67, 90,
      ]),
      gl.STATIC_DRAW);
}

main();
@import url("https://webglfundamentals.org/webgl/resources/webgl-tutorials.css");
body {
  margin: 0;
}

canvas {
  width: 100vw;
  height: 100vh;
  display: block;
}
<canvas id="canvas"></canvas>
<div id="uiContainer">
  <div id="ui">
    <div id="moveSpeed"></div>
  </div>
</div>
<!-- vertex shader -->
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

uniform vec2 u_resolution;
uniform vec2 u_translation;

void main() {
   // Add in the translation.
   vec2 position = a_position + u_translation;

   // convert the position from pixels to 0.0 to 1.0
   vec2 zeroToOne = position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
</script>
<!-- fragment shader -->
<script id="2d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform vec4 u_color;

void main() {
   gl_FragColor = u_color;
}
</script><!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/webgl-lessons-ui.js"></script>


推荐阅读