As I mentioned in my previous post, I have been working on a graphics rendering library for the html5 canvas element. Peint is an attempt to make using canvas easier and more flexible, while introducing event-based programming. You include only the core library and then use Peint.require(‘yourscript’, callback) to asynchronously load extra modules and execute the callback code once the module is ready. Using this method, http requests are made smaller and occur after page load, so execution appears near instant–no waiting for 100+ kb of code to download before the system starts setting itself up.
In the previous post, I showed you the viewport module, which allowed me to dynamically resize the canvas to cover the entire viewport and adjust itself automatically whenever the window is resized. This time I’ll be introducing part of the draw2d module. Canvas uses the fillRect() method to fill a rectangular area with a particular color, but it only suppports the standard pixel coordinates from a top left origin. I decide that wasn’t good enough for me.
In the example below, we fill the background with a pleasant blue color, and we draw 2 boxes using a mix of numeric pixel coordinates, css-style ’100px’ coordinates and even percentages. In addition to that, it also demonstrates positioning from a non-top/left origin! The canvas.coords() positioning system dynamically tranforms the input values using their key names and the current dimensions of the canvas, allowing lots of flexibility in element positioning. I have a neat demo showing the fill() and image() methods online here; peint.stephenbelanger.com
// Initialize our canvas screen.
var screen = Peint.init('#screen');
// Load draw2d module for basic 2D drawing tools.
Peint.require('draw2d', function(){
var canvas = this;
// Draw our background color.
canvas.fill(canvas.rgb(0,100,130));
// Draw some boxes...
// This one is statically positioned with pixels.
// 'px' is optional, it will assume that on numbers.
canvas.fill(
canvas.rgba(150,200,0,0.8)
, canvas.coords({
right:150
, bottom:150
, width:'100px'
, height:'100px'
})
);
// This one is dynamically positioned with percentages.
canvas.fill(
canvas.rgba(200,150,0,0.8)
, canvas.coords({
left:'2%'
, top:'5%'
, width:'15%'
, height:'50%'
})
);
});