Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. WebGL: 2D and 3D graphics for the web
  4. WebGL tutorial
  5. Animating objects with WebGL

Animating objects with WebGL

Making the square rotate

In this example, we'll actually rotate our camera. By doing so, it will look as if we are rotating the square. First we'll need some variables in which to track the current rotation of the camera.

Note:Add this code at the start of your "webgl-demo.js" script:

js
let squareRotation = 0.0;let deltaTime = 0;

Now we need to update thedrawScene() function to apply the current rotation to the camera when drawing it. After translating the camera to the initial drawing position for the square, we apply the rotation.

In your "draw-scene.js" module, update the declaration of yourdrawScene() function so it can be passed the rotation to use:

js
function drawScene(gl, programInfo, buffers, squareRotation) {  // …}

In yourdrawScene() function, right after the linemat4.translate() call, add this code:

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

This rotates the modelViewMatrix by the current value ofsquareRotation, around the Z axis.

To actually animate, we need to add code that changes the value ofsquareRotation over time.

Add this code at the end of yourmain() function, replacing the existingdrawScene() call:

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

This code usesrequestAnimationFrame to ask the browser to call the functionrender on each frame.requestAnimationFrame passes us the time in milliseconds since the page loaded. We convert that to seconds and then subtract from it the last time to computedeltaTime, which is the number of second since the last frame was rendered.

Finally, we updatesquareRotation.

View the complete code |Open this demo on a new page

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp