Skip to content

Instantly share code, notes, and snippets.

@lazyTai
Created September 24, 2017 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazyTai/6498682f08e1b773506d6f2d55377ebc to your computer and use it in GitHub Desktop.
Save lazyTai/6498682f08e1b773506d6f2d55377ebc to your computer and use it in GitHub Desktop.
requestAnimationFrame demo
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>requestAnimationFrame</title>
</head>
<body>
<style>
#canvas {
}
</style>
<canvas id="canvas" width="600" height="600"></canvas>
<button id="start">start</button>
<button id="end">end</button>
<script>
var cc = console;
(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
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);
};
}());
var canvas = document.querySelector("#canvas")
var ctx = canvas.getContext("2d");
var x = 0;
var speed = 10;
var idAnimation = 0;
ctx.fillStyle = '#eee';
ctx.fillRect(0, 0, 100, 100);
var startHand = function () {
idAnimation = window.requestAnimationFrame(startHand)
if (x >= 600) {
window.cancelAnimationFrame(idAnimation)
return false
}
ctx.clearRect(0, 0, 600, 600);
x = x + speed;
ctx.fillRect(x, 0, 100, 100)
}
document.querySelector('#start').addEventListener("click", function (e) {
e.preventDefault();
idAnimation = window.requestAnimationFrame(startHand)
})
document.querySelector('#end').addEventListener("click", function (e) {
e.preventDefault();
window.cancelAnimationFrame(idAnimation)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment