gury: A jQuery-inspired chainable JavaScript helper for HTML5 Canvas
With more and more browser and mobile device support, adoption of the HTML5 <canvas>
object is accelerating. For developers who are used to working with JavaScript libraries, using the native Canvas JavaScript APIs might seem a bit cumbersome.
Ryan Sandor Richards aims to wrap those Canvas APIs in a bit of jQuery-inspired convenience. Gury, pronounced “jury”, introduces some basic chaining, allowing you to build your canvas scenes and animate them in one expression.
Usage
To use Gury, reference the Gury script in your document’s <HEAD>
and add a <canvas>
element with an DOM Id to your page. Use the $g
function to operate on your canvas to set size and colors, add objects, and finally call draw()
.
$(function() {
// Get the canvas as a gury object
$g('screen')
// set its size,
.size(256, 256)
// and background color
.background('#111')
// Now add a simple function that draws a diagonal line
.add(function(ctx) {
ctx.strokeStyle = '#f00';
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(246, 246);
ctx.stroke();
})
// Draw the scene's objects onto the canvas
.draw()
});
Animation
Gury also handles animation. Simply call play()
passing in the refresh interval in milliseconds.
$(function() {
// Get the canvas as a gury object
$g('screen')
// set its size,
.size(256, 256)
// and background color
.background('#111')
// Add a more complicated animated object
.add({
x: 20, y: 20, dx: 1, dy: 2, s: 10,
draw: function(ctx) {
ctx.fillStyle = "#0ff";
ctx.fillRect(this.x, this.y, this.s, this.s);
this.x += this.dx;
if (this.x >= 246 || this.x <= 10) {
this.dx *= -1;
}
this.y += this.dy;
if (this.y >= 246 || this.y <= 10) {
this.dy *= -1;
}
}
})
// Draw the scene's objects onto the canvas
.draw()
// And finally begin playing the animation!
.play(16);
});
Ryan has some excellent demos in the repository, including this simple color matching puzzle:
Discussion
Sign in or Join to comment or subscribe