Skip to content

Instantly share code, notes, and snippets.

@akilism
Last active August 29, 2015 14:17
Show Gist options
  • Save akilism/31380d3f097852083649 to your computer and use it in GitHub Desktop.
Save akilism/31380d3f097852083649 to your computer and use it in GitHub Desktop.
my tiny canvas starter
var cnvs = (function() {
var canvas,
ctx,
isCanvasEnabled,
drawPending,
canvasHeight,
canvasWidth,
time = 0,
counter = 0,
c,
clickX,
clickY,
moveX,
moveY;
var setCanvas = function(can) {
canvas = can;
if(canvas.getContext) {
ctx = canvas.getContext('2d');
canvasHeight = canvas.height;
canvasWidth = canvas.width;
isCanvasEnabled = true;
canvas.addEventListener('click', onClick);
// canvas.addEventListener('mousemove', onMouseMove);
} else {
isCanvasEnabled = false;
}
};
var tick = function(delta) {
update();
redraw();
};
var render = function() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
c = c || new Circle(canvasWidth/2, canvasHeight/2, 100, '#dfdfdf');
c.draw(ctx);
};
var run = function(timestamp) {
drawPending = false;
var delta = timestamp - time;
time = timestamp;
tick(delta);
render();
};
var onClick = function(evt) {
clickX = evt.clientX;
clickY = evt.clientY;
console.log('click', clickX, clickY);
};
var onMouseMove = function(evt) {
moveX = evt.clientX;
moveY = evt.clientY;
// console.log('move', moveX, moveY);
};
var redraw = function() {
if(!drawPending) {
drawPending = true;
requestAnimationFrame(run);
}
};
var update = function() {
};
var Circle = function(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.endAngle = 2*Math.PI;
};
Circle.prototype.draw = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, this.endAngle, false);
ctx.fillStyle = this.color;
ctx.fill();
};
return {
setCanvas:setCanvas,
redraw:redraw,
isCanvasEnabled: function() { return isCanvasEnabled; }
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment