Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created October 5, 2012 16:44
Show Gist options
  • Save ashblue/3840915 to your computer and use it in GitHub Desktop.
Save ashblue/3840915 to your computer and use it in GitHub Desktop.
HTML5 Canvas Pre-Rendering
/**
* A simple object for creating pre-rendered Canvas elements on the fly without
* creating a mess in your files.
* @author Ash Blue [email protected]
* @link http://blueashes.com
*
* @example
* // Create a new pre-renderd Canvas and draw on it (width, height, drawLogic)
* var myPreRender = new PreRender(50, 50, function (ctx) {
* ctx.fillStyle = '#000';
* ctx.fillRect(0, 0, 50, 50);
* });
*
* // You can also clear out the current pre-render and draw something new
* // See the PreRender's methods below for more functionality
* myPreRender.setDraw(function (ctx) {
* ctx.fillStyle = '#777';
* ctx.fillRect(0, 0, 50, 50);
* });
*/
(function (document) {
var _private = {
/**
* Creates a new rendering Canvas on the fly and returns it
* @returns {object}
*/
createCanvas: function () {
var el = document.createElement('canvas');
return el;
}
};
/**
* Creates a new pre rendering Canvas, sets up the ctx, sets Canvas size
* and executes a draw on the Canvas if passed
* @param {number} width Width of the canvas in pixels
* @param {number} height Height of the canvas in pixels
* @param {function} [drawLogic] Logic to draw a single frame onto the
* canvas
* @returns {self}
*/
var PreRender = function (width, height, drawLogic) {
// Create and setup Canvas
this.canvas = _private.createCanvas();
this.ctx = this.canvas.getContext('2d');
this.setSize(width, height);
// Draw onto the Canvas
if (typeof drawLogic === 'function') {
this.setDraw(drawLogic);
}
return this;
};
/**
* Clears out the pre-rendered Canvas with the pre-defined width and height
* @returns {self}
*/
PreRender.prototype.cleanCanvas = function() {
this.ctx.clearRect(0, 0, this.width, this.height);
return this;
};
/**
* Replaces the previously drawn frame on the Canvas
* @param {function} drawLogic Logic for drawing the new frame
* @returns {self}
*/
PreRender.prototype.setDraw = function (drawLogic) {
this.cleanCanvas();
drawLogic(this.ctx);
return this;
};
/**
* Change the size of the rendering Canvas
* @param {number} width Width in pixels
* @param {number} height Height in pixels
* @returns {self}
*/
PreRender.prototype.setSize = function (width, height) {
this.canvas.width = width;
this.canvas.height = height;
return this;
};
return PreRender;
}(document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment