Web Animations API
by Brian Birtles
HTML
<div id="fan"></div>
<button id="cw">clockwise</button>
<button id="ccw">counter-clockwise</button>
<button id="stop">stop</button>
CSS
#fan {
width: 150px;
height: 150px;
background-color: red;
left: 50%;
position: absolute;
top: 50%;
}
#fan div {
border: 1px solid black;
margin-left: -50%;
margin-top: -50%;
}
#cw,
#ccw,
#stop {
background-color: light-blue;
border: 1px solid black;
width: 200px;
height: 50px;
}
JavaScript
const fan = document.getElementById('fan');
const fananim = fan.animate(
[
{
transform: 'rotate(0)',
},
{
transform: 'rotate(360deg)',
},
],
{
duration: 8000,
iterations: Infinity,
}
);
fananim.pause();
// Give us some range to travel backwards.
// One million iterations ought to do it.
fananim.currentTime = 8000 * 1000000;
function clockwise() {
if (fananim.playbackRate < 0) {
fananim.reverse();
} else if (fananim.playState !== 'running') {
fananim.play();
}
}
function counterclockwise() {
if (fananim.playbackRate > 0) {
fananim.reverse();
} else if (fananim.playState !== 'running') {
fananim.play();
}
}
function stop() {
fananim.pause();
}
const ela = document.getElementById('cw');
ela.addEventListener('click', clockwise, false);
const elb = document.getElementById('ccw');
elb.addEventListener('click', counterclockwise, false);
const elc = document.getElementById('stop');
elc.addEventListener('click', stop, false);