when learning requestAnimFrame, I want to use window.cancelAnimationFrame to stop animation, but I don"t know how to use it correctly. The
code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
-sharprequestAnim{
position: absolute;
width: 100px;
height: 100px;
background-color: -sharpccc;
}
-sharpaaa{
position: absolute;
top: 100px;
}
</style>
</head>
<body>
<div id="requestAnim">
</div>
<button id="aaa" onclick="restop();"></button>
<script>
(function() {
var lastTime = 0;
var vendors = ["ms", "moz", "webkit", "o"];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; PPx) {
window.requestAnimationFrame = window[vendors[x]+"RequestAnimationFrame"];
window.cancelAnimationFrame = window[vendors[x]+"CancelAnimationFrame"] || window[vendors[x]+"CancelRequestAnimationFrame"];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
window.requestAnimFrame = (function(){//
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
} )();
var elem = document.getElementById("requestAnim");
var startTime = undefined;//
function render(time){//time
if (time === undefined)
time = Date.now();//
if (startTime === undefined)
//startTimeundefined
//time
startTime = time;
//500left0
elem.style.left = ((time - startTime)/10%500) + "px";
}
elem.onclick = function(){
(function animloop(){
render();
//requestAnimFrame
requestAnimFrame(animloop);
})();
}
function restop(){
window.cancelAnimationFrame(animloop);
}
</script>
</body>
</html>