Skip to content

Instantly share code, notes, and snippets.

@devyn
Created November 11, 2009 07:52
Show Gist options
  • Save devyn/231765 to your computer and use it in GitHub Desktop.
Save devyn/231765 to your computer and use it in GitHub Desktop.
function Animation(canvasId, fps) {
this.canvas = document.getElementById(canvasId);
this.drawingContext = this.canvas.getContext('2d');
this.fps = fps;
this.drawing = {};
this.frame = 0;
this.start();
}
Animation.prototype.start = function() {
var t = this;
this.animProcess = setInterval(function(){t.draw();}, Math.round(1.0/this.fps*1000));
this.running = true;
};
Animation.prototype.draw = function() {
this.drawingContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (name in this.drawing)
this.drawing[name](this.drawingContext, this.frame); // run drawing procedure
this.frame += 1;
};
Animation.prototype.pause = function() {
if (!this.running) return;
clearInterval(this.animProcess);
this.running = false;
};
Animation.prototype.reset = function() {
this.frame = 0;
};
Animation.prototype.stop = function() {
if (!this.running) return;
this.pause();
this.reset();
};
<html>
<head>
<title>Devyn's Canvas Test</title>
<script src="canvas-animation.js"></script>
<script>
var anim;
function init() {
anim = new Animation('canvas', 30);
anim.drawing.square = function(ctx, frame) {
ctx.save();
ctx.translate(60, 60);
ctx.rotate(Math.PI/180 * (frame % 360));
ctx.fillStyle = "rgb(40,40,40)";
ctx.fillRect(-30,-30,60,60);
ctx.restore();
};
anim.drawing.innerSquare = function(ctx, frame) {
ctx.save();
ctx.translate(60, 60);
ctx.rotate(Math.PI/180 * (frame*3 % 360));
ctx.fillStyle = "#00ffff";
ctx.fillRect(-15,-15,30,30);
ctx.restore();
};
}
</script>
</head>
<body onload="init();">
<div><canvas id="canvas" width="120" height="120"></canvas></div>
<div>
<a href="#" onclick="if (anim.running) anim.pause(); else anim.start();">Play/Pause</a> |
<a href="#" onclick="anim.stop();">Stop</a>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment