Java Reference
In-Depth Information
var square = document.getElementById("square");
var angle = 0;
setInterval(function() {
angle = (angle + 5)%360
square.style.transform = "rotate(" + angle + "deg)"
}, 1000/6)
This code receives a reference to our square div and then sets a variable called
angle
to 0.
We then use the
setInterval()
method to increase the value of
angle
by
5
(we also
use the
%
operator so that it resets to 0 at 360), then set the
transform
CSS3 property
to rotate that number of degrees. The second argument is
1000/60
, which equates to a
frame speed of 60 frames per second.
Open animation.htm in your browser and you should see a rotating square, although it will
probably be quite slow and not very smooth. This was the only way to achieve animation
using JavaScript until the
window.requestAnimationFrame()
method was deve-
loped.
requestAnimationFrame
This method of the
window
object works in much the same way as the
win-
dow.setInterval()
method, although it has a number of improvements to optimize
its performance. These include making the most of the browser's built-in graphics-handling
capabilities and not running the animation when the tab is inactive, resulting in a much
smoother performance. It is supported in all major browsers, including Internet Explorer
from version 10 onwards. Change the code in scripts.js to the following:
var square = document.getElementById("square");
var angle = 0;
function rotate() {
angle = (angle + 5)%360
square.style.transform = "rotate(" + angle + "deg)"
window.requestAnimationFrame(rotate);
}