Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created February 2, 2012 18:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tbranyen/1724907 to your computer and use it in GitHub Desktop.
Save tbranyen/1724907 to your computer and use it in GitHub Desktop.
Lightweight canvas wrapper.
// Basic Usage:
//
// var main = new Canvas({ elem: "canvas" }, function(options) {
// // Instantiate anything specific here...
// // Main draw loop
// this.draw = function() {
//
// };
// });
//
// Canvas
function Canvas(opts, initialize) {
// Used to cache user defined draw method
var drawCache;
var drawObj = { now: +new Date, last: +new Date };
// Set defaults
this.width = opts.width || 320;
this.height = opts.height || 240;
this.fps = opts.fps || 30;
// Query the DOM for canvas element using a selector
if (opts.canvas && typeof opts.canvas == "string") {
this.canvas = document.querySelector(opts.canvas);
// Set to element || undefined
} else {
this.canvas = opts.canvas;
}
// Initialize with the options
initialize.call(this, opts);
// Set the width/height on the canvas element
this.canvas.width = this.width;
this.canvas.height = this.height;
// Set the 2d context
this.ctx = this.canvas.getContext("2d");
// Set correct fps
this.fps = 1000 / this.fps;
// Set to nop if user does not provide a function
drawCache = this.draw || function() {};
// Wrap draw method
this.draw = function() {
var canvas = this;
drawObj.now = +new Date;
drawCache.call(canvas, drawObj);
// Set draw loop
window.setTimeout(function() {
requestAnimFrame(canvas.draw);
}, canvas.fps);
}.bind(this);
}
// Draw methods
Canvas.prototype = {
G: 6.673e-1,
clear: function() {
this.rect(0, 0, this.width, this.height);
},
start: function() {
this.clear();
this.draw();
},
rect: function(x, y, width, height) {
this.ctx.fillRect(x, y, width, height);
},
line: function(px, py, x, y) {
this.ctx.beginPath();
this.ctx.moveTo(px, py);
this.ctx.lineTo(x, y);
this.ctx.closePath();
this.ctx.fill();
this.ctx.stroke();
},
circle: function(x, y, radius) {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, Math.PI * 2, true);
this.ctx.closePath();
this.ctx.fill();
},
distance: function(x2, x1, y2, y1) {
return Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
},
angleFromPoints: function(x1, x2, y1, y2) {
return Math.atan2(y2-y1, x2-x1);
},
random: function(min, max, decimal) {
if (decimal) {
return Math.random() * (max - min) + min;
}
return Math.floor(Math.random() * (max - min+1)) + min;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment