Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. WebGL:web 中的 2D 的 3D 图形
  4. WebGL 教程
  5. 用 WebGL 让目标动起来

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

用 WebGL 让目标动起来

在此示例中,我们实际上将旋转正方形平面。

使正方形旋转

让我们开始旋转正方形。我们需要的第一件事是创建一个变量,用于跟踪正方形的当前旋转:

js
var squareRotation = 0.0;

现在我们需要更新drawScene()函数以在绘制正方形时将当前旋转应用于正方形。转换为正方形的初始绘图位置后,我们像这样应用旋转:

js
mat4.rotate(  modelViewMatrix, // destination matrix  modelViewMatrix, // matrix to rotate  squareRotation, // amount to rotate in radians  [0, 0, 1],); // axis to rotate around

这会将 modelViewMatrix 的当前值squareRotation绕 Z 轴旋转。

要进行动画制作,我们需要添加squareRotation随时间更改值的代码。为此,我们可以创建一个新变量来跟踪上次动画播放的时间(我们称之为then),然后将以下代码添加到主函数的末尾

js
var then = 0;// Draw the scene repeatedlyfunction render(now) {  now *= 0.001; // convert to seconds  const deltaTime = now - then;  then = now;  drawScene(gl, programInfo, buffers, deltaTime);  requestAnimationFrame(render);}requestAnimationFrame(render);

该代码用于requestAnimationFrame 要求浏览器在每一帧上调用函数“render”。requestAnimationFrame 自页面加载以来经过的时间(以毫秒为单位)。我们将其转换为秒,然后从中减去,以计算deltaTime 自渲染最后一帧以来的秒数。在 drawscene 的结尾,我们添加了要更新的代码squareRotation

js
squareRotation += deltaTime;

该代码使用自上次我们更新值以来所经过的时间squareRotation来确定旋转正方形的距离。

查看完整代码 |在新页面中打开示例

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp