see whatever…

jump to menu

August 7, 2010

HTML5 canvas API chainable (jQuery like)

Filed under: HTML5,Javascript — see @ 7:01 pm

While playing around with HTML5 canvas (with jQuery on the page) I noticed the rather tedious writing of

canvas = $('canvas')
ctx canvas.get(0).getContext('2d')
ctx.dothis...
ctx.dothat...

So I thought a jQuery like chaining syntax would be nice. Only first try but it seems actually quite simple. Code I came up with:

function jqContext(canvas) {
	function jqContext(canvas) {
	/* Canvas 2D Context wrapper allowing jQuery like chaining */
	var self = this
	self.context = canvas.get(0).getContext('2d')
	
	// wrap properties of context chainable, without argument
    // returning current value, with argument setting value
	$(['fillStyle'
	   ,'font'
	   ,'strokeStyle'
	   ,'textAlign' ,'textBaseline'
	   ,'mozImageSmoothingEnabled'
	]).each(function() {
		 var property = this
		 self[property] = function(a) {
		  	 if (a != undefined) {
		 		 self.context[property] = a
				 return self 
			 } else {
				 return self.context[property]
			 }
		 }
	})
	// wrap methods of context
	$(['arc',
	   'beginPath', 'closePath'
	   ,'drawImage' //?
	   ,'fillText', 'strokeText'
	   ,'lineTo'
	   ,'moveTo',
	   ,'fillRect', 'strokeRect', 'clearRect'
	   ,'stroke'
	]).each(function() {
	    var method = this
	    self[method] = function() {
		    self.context[method].apply(self.context, arguments)
		    return self			
	    }
    })
	// wrap methods of context NOT chainable
	$(['createLinearGradient'
	]).each(function() {
	    var method = this
	    self[method] = function() {
		    return self.context[method].apply(self.context, arguments)
	    }
    })
}

So now I can write:

c = $('<canvas></canvas>').appendTo('body')
c.css({
	width: 800,
	height: 400,
	border: '1px solid #ccc'
})

x = new jqContext(c)
x
.strokeStyle('#f00')
.strokeRect(0,0, 100, 100)
.fillRect(40,50, 100, 100)
.clearRect(70,50, 80, 100)

Don’t know if worth the effort and only a test (not complete at all obviously) but fun ;)

UPDATE: Improved the class a bit, calling a property wrapper with no value returns the current value now, also added a few more methods…

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress