In this article
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:
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:
function drawScene(gl, programInfo, buffers, squareRotation) { // …}In yourdrawScene() function, right after the linemat4.translate() call, add this code:
mat4.rotate( modelViewMatrix, // destination matrix modelViewMatrix, // matrix to rotate squareRotation, // amount to rotate in radians [0, 0, 1],); // axis to rotate aroundThis 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:
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.