Object-based canvas drawing
with oCanvas

oCanvas logo

oCanvas is a JavaScript library that makes canvas development easier to understand and do, by creating a bridge between the native pixel drawing approach and objects that are created and added to canvas. It is now possible to very easily create objects, change properties of these objects and add events to them—and everything just works because oCanvas handles the background stuff for you.

Development of oCanvas started in the summer of 2010. It was under heavy development for a few months and was later put on ice until January 2011 when I started the development again. It went through a total restructure and was improved a lot. In March 2011 it was ready for the first release.

Check out the oCanvas website for more info.

To start using oCanvas you need to include a copy of oCanvas either by including the CDN-hosted file, or a file you host yourself. Then in your own JavaScript file, you write the following piece:

var canvas = oCanvas.create({
	canvas: "#canvas",
	background: "#222",
	fps: 60
});

That code initializes a core instance of oCanvas, which will enable you to create objects and everything. You can also pass more things to that create() method. The canvas parameter is a CSS selector and must point to a canvas element that is present in the DOM.

oCanvas has a few different predefined shapes, but you can also create your own. To create a rectangle, you simply write this:

var rectangle = canvas.display.rectangle({
	x: 50,
	y: 100,
	width: 100,
	height: 50,
	fill: "#f00"
});
canvas.addChild(rectangle);

The object has then been created, and the last line adds it to the canvas. Besides just adding an object to the canvas, you can also add objects as children to other objects.

A big feature of oCanvas is that you can add events to specific objects. It supports events for mouse, touch and keyboard. This can look like this:

rectangle.bind("click tap", function (e) {
	this.rotate(10);
	canvas.redraw();
});

As you can see, you can bind to both mouse and touch events very easily. Clicking or tapping on this rectangle will rotate it 10 degrees clockwise.

This is just an introduction to show you what the API looks like. Go to the website for more information and documentation.

Images

Documentation on oCanvas website
The documentation on the oCanvas website.