Skip to content

Instantly share code, notes, and snippets.

@ComFreek
Created December 27, 2012 17:17
Show Gist options
  • Save ComFreek/4390055 to your computer and use it in GitHub Desktop.
Save ComFreek/4390055 to your computer and use it in GitHub Desktop.
CircleAnimater - animates any DOM object like a circle
// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
function CircleAnimater(elem, radius, speed) {
this.elem = elem;
this.radius = radius;
this.angle = 0;
this.origX = this.elem.offsetLeft;
this.origY = this.elem.offsetTop;
this.shouldStop = false;
this.lastFrame = 0;
this.speed = speed;
}
CircleAnimater.prototype.start = function () {
this.lastFrame = +new Date;
this.shouldStop = false;
this.animate();
}
CircleAnimater.prototype.stop = function () {
this.shouldStop = true;
}
CircleAnimater.prototype.animate = function () {
var now = +new Date,
deltaT = now - this.lastFrame;
var newY = Math.sin(this.angle) * this.radius;
var newX = Math.cos(this.angle) * this.radius;
this.elem.style.left = (this.origX + newX) + "px";
this.elem.style.top = (this.origY + newY) + "px";
this.angle += (this.speed * deltaT);
this.lastFrame = +new Date;
if (!this.shouldStop) {
var $this = this;
requestAnimFrame(function () {
$this.animate();
});
}
}
<!doctype html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<button id="btnStart">Start</button> - <button id="btnStop">Stop</button>
<hr />
<div id="myDiv">Hello World!</div>​
<script src="circleAnimater.js"></script>
<script>
var elem = document.getElementById("myDiv");
var ca = new CircleAnimater(elem, 250, Math.PI / 5000);
document.getElementById("btnStart").onclick = function () {
ca.start();
};
document.getElementById("btnStop").onclick = function () {
ca.stop();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment