-
Notifications
You must be signed in to change notification settings - Fork 23
/
08_requestAnimationFrame.html
78 lines (70 loc) · 2.39 KB
/
08_requestAnimationFrame.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
// 统一前缀
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // Webkit中此取消方法的名字变了
window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
// 不支持则采用setTimeout
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16.7 - (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);
};
}
}());
var box = document.getElementById("box");
console.log(window.requestAnimationFrame);
function draw() {
if (box.offsetLeft <= 300) {
box.style.left = box.offsetLeft + 10 + "px";
return false;
} else {
return true;
}
}
function makeRAFLoop(frameFn, context) { //requestAnimationFrame的递归调用的启动函数
var isEnd = false,
RAFId = -1;
(function rafLoop() { // 通过具名自执行函数,完成requestAnimationFrame的递归调用,frameFn需要返回动画是否完成的标志量
isEnd = frameFn.call(context);
RAFId = window.requestAnimationFrame(rafLoop);
if (isEnd) {
window.cancelAnimationFrame(RAFId);
}
})();
}
makeRAFLoop(draw, window); // 启动
</script>
</body>
</html>